Sunday, September 18, 2016

Migrate SHA1 Salted Hashes To Be Encrypted by Bcrypt | Fixed issues

Migrate SHA1 Salted Hashes To Be Encrypted by Bcrypt | Fixed issues


Migrate SHA1 Salted Hashes To Be Encrypted by Bcrypt

Posted: 18 Sep 2016 08:05 AM PDT

I have an old application (built on .Net C#) includes Users table with hashed passwords sha1(password . salt), and I need to migrate this data safely to my new Rails application (which already encrypting passwords using bcrypt-ruby gem) and looking for the best solution for this issue but with avoiding the following kind of solutions:

  1. Reset all current users' passwords and Force them to proceed 'Forget password' procedure
  2. Use any kind of plain text password (even temporarily while user login for first time into my new application for example).
  3. Use SHA1 same encryption procedure in Rails app also (I need to use BCrypt instead).

I think that the best approach (as I've read) is to let users log into my new app using their old passwords (and I don't know how to do it) and then encrypt their passwords (by BCrypt) and follow the same procedure of newly registered users' password encryption in Rails app.

I appreciate all suggested solutions to solve this issue.

Passing multiple fields values to ransack

Posted: 18 Sep 2016 08:23 AM PDT

I have Rails app with a table and I want to have search fields on top of each column which should perform search on the column and those searches should work together. So I'm looking for a way to implement it and stumbled upon Ransack gem which looks nice with all it's selecting and sorting functionality but I can't understand if I can use it to solve my problem.

From the documentation I see that I can pass a parameter to it like this User.ransack(first_name_cont: 'Rya').result.to_sql

But I think it's not enough for my problem and I need something like User.ransack(first_name_cont: 'Foo', last_name_eq: 'Bar', middle_name_in: [Moo, Boo]).result.to_sql

Can I do something like this with Ransack? Or how else can I solve my problem with it or maybe I should use something else?

Adding text on button click to simple form with jquery

Posted: 18 Sep 2016 07:37 AM PDT

I'm starting out with jQuery, and I'm trying to add bootstrap buttons that add Spanish-accent vowels to the simple_form text field on click. I'm modeled the code after an answer to this question, but nothing is currently happening upon clicking the button--am I doing something wrong?

In the view, I'm using simple form and adding a wrapper id to the text field:

<%= simple_form_for @word, url: lesson_image_spelling_path(current_lesson, @word.word), method: :patch do |f| %>      <%= f.input :spelling_attempt, wrapper_html: { id: 'txt' }, label: "Spell the word:" %>        <br>        <button type="button" class="btn btn-secondary btn-sm" id="a-accent">รก</button>        <%= f.button :submit, "Submit", class: 'btn btn-primary' %>  <% end %>  

In application.js I have:

jQuery("#a-accent").on('click', function() {    var $txt = jQuery("#txt");    var caretPos = $txt[0].selectionStart;    var textAreaTxt = $txt.val();    var txtToAdd = "test";    $txt.val(textAreaTxt.substring(0, caretPos) + txtToAdd + textAreaTxt.substring(caretPos) );  });  

Morris.js how to create graph for specific type

Posted: 18 Sep 2016 07:57 AM PDT

I have some troubles with create graph using Morris.js library. I created sport app and every training has some values. One of them is "workout" it means type of workout("Running","Swimming","Cycling"). I want to display line graph with date and distance, but for specific type of training, for example "Running". I created general graph with all dates and distances, but when I try to make graph for specific type it doesn't display proper one, but graph with sum of all running distances for every day(horizontal line). I don't know how to fix line in workouts_helper.rb distance: Workout.where(workout: "Running").sum(:distance)

workouts_helper.rb :

def running_chart_data      (3.weeks.ago.to_date..Date.today).map do |date|          {              date: date,              distance: Workout.where(workout: "Running").sum(:distance)          }      end  end  

application.html.erb :

<script>          new Morris.Line({            element: 'running_chart',            resize: true,            data: $('#running_chart').data('running'),            xkey: 'date',            ykeys: ['distance'],            labels: ['Distance']          });  </script>  

index.html.erb :

<h1>Last 3 weeks running graph</h1>            <%= content_tag :div, "", id: "running_chart", data: {running: running_chart_data} %>  

Refactoring (sorting) code with React and Rails

Posted: 18 Sep 2016 07:25 AM PDT

I'm working on a React-Rails app in ES6, and I'm trying to figure out the best way to refactor my code.

For example, within one of my main React components, I have a couple of methods that manage merge-sorting my results. Where should that sorting code live?

I'm trying to figure out the best practices with React and Rails to keep my code as DRY and SRP-mindful as possible.

Active admin / Carrierwave multiple image upload

Posted: 18 Sep 2016 07:55 AM PDT

I've been struggling for a week now, I'm trying to create a form inside active_admin where a user can select several pictures, add a description and a title, then submitting his form to create something that would look like a gallery

So far, I have two models created with the commands:

rails g model Gallery title:string description:text  rails g model Image url:text #just in case the user has LOTS of images to upload  

Here are how look my models now:

gallery.rb

class Gallery < ApplicationRecord    has_many :images    accepts_nested_attributes_for :images, allow_destroy: true  end  

image.rb

class Image < ApplicationRecord      belongs_to :gallery    mount_uploader :image, ImageUploader #Using Carrier Wave  end  

admin/gallery.rb

  permit_params :title, :description, :images      form html: { multipart: true }  do |f|      f.inputs  do        f.input :title        f.input :description        f.input :images, as: :file, input_html: { multiple: true }      end      f.actions    end  

My problem is that even though my 'image' form shows up, I can't manage to save the images through the other model, nothing gets uploaded inside my 'public/upload' directory, and nothing gets written inside my database.

I can't find anything interesting internet that could solve this problem

Feel free to ask for another file

Any help welcome

password_field_tag submits FILTERED value

Posted: 18 Sep 2016 07:57 AM PDT

I am new to rails and I am making a simple login page.

this is the code of my view

<%= form_tag(:action => 'signup') do %>      <div class="row">        <!-- first name -->        <div class="col-md-6">          <div class="form-group">            <%= label_tag('instructor_firstname', 'First Name:') %>            <%= text_field_tag 'instructor[firstname]', nil, class: 'form-control', required: true %>          </div>        </div>        <!-- first name -->        <!-- last name -->        <div class="col-md-6">          <div class="form-group">            <%= label_tag('instructor_lastname', 'Last Name:') %>            <%= text_field_tag 'instructor[lastname]', nil, class: 'form-control', required: true %>          </div>        </div>        <!-- last name -->      </div>        <!-- User ID -->      <div class="row">        <div class="col-md-12">          <div class="form-group">            <%= label_tag('instructor_id', 'Instructor ID:') %>            <%= text_field_tag 'instructor[id]', nil, class: 'form-control', required: true %>          </div>        </div>      </div>      <!-- User ID -->        <!-- password-->      <div class="row">        <div class="col-md-12">          <div class="form-group">            <%= label_tag('password', 'Password:') %>            <%= password_field_tag 'password', nil, class: 'form-control', required: true %>          </div>        </div>      </div>      <!-- password-->        <!-- confirm password-->      <div class="row">        <div class="col-md-12">          <div class="form-group">            <%= label_tag('confirmpassword', 'Confirm Password') %>            <%= password_field_tag 'confirmpassword', nil, class: 'form-control', required: true %>          </div>        </div>      </div>      <!-- confirm password-->        <!-- error message -->      <% if !flash[:error].blank? %>        <div class="row">          <div class="col-md-12">            <p><i><small><%= flash[:error] %></small></i></p>          </div>        </div>      <% end %>      <!-- error message -->        <!-- Signup button -->      <div class="row">        <div class="text-center">          <%= submit_tag 'Sign up', class: 'btn btn-default' %>        </div>      </div>      <!-- Signup button -->  <% end %>  

but when I check the parameters submitted the result is

"instructor"=>{"firstname"=>"Gerald", "lastname"=>"Campana", "id"=>"2112"}, "password"=>"[FILTERED]", "confirmpassword"=>"[FILTERED]", "commit"=>"Sign up"}  

I can't compare the two password, even if I tried to display it to the console using puts params[:instructor][:password] it shows nothing

Rails: Paperclip 4 - Renaming a file during creation

Posted: 18 Sep 2016 06:43 AM PDT

I have a Rails application with Paperclip 4 where there are products with images. Now, I want after an image is uploaded to rename the image to the product name.

e.g.

Product: Really tasty sandwich Image: really-tasty-sandwich-1.png

The number at the end should be equal to the amount of images which the product possesses.

I tried interpolators but they don't really work for my case since I want the first image to be called really-tasty-sandwich-1.png and the second really-tasty-sandwich-2.png but interpolators changes both to really-tasty-sandwich-2.png since it is dynamically. The amount of images per product is available through product.images.count since it is a separate model.

So what I need is some logic which renames the image so a user can upload an image with whatever name he wants and it will be renamed correctly.

Does somebody have an idea how it works? Probably something with callbacks I guess.

Thanks

Edit:

My image model logic so far:

has_attached_file :image,                  path: ':rails_root/public/product_images/:attachment/:id_partition/:normalized_filename',                  url: '/product_images/:attachment/:id_partition/:normalized_filename'    Paperclip.interpolates :normalized_filename do |attachment, style|    if attachment.instance.product.present?      attachment.instance.normalized_filename(attachment.content_type)    else      attachment.original_filename    end  end    def normalized_filename(content_type)    "#{product.name.downcase.split(' ').join('-')}-#{product.images.count}.#{content_type.split('/').last}"  end  

ActiveModelSerializer not kicking in

Posted: 18 Sep 2016 07:09 AM PDT

I want to serialize the newly created resource in this action :

def create      @comment = @commentable.comments.build(comment_params)      @comment.user = current_user      respond_to do |format|        if @comment.save          format.json { render json: @comment }          format.html { redirect_to @question, notice: "Comment successfully created." }        else            format.html { render 'questions/show' }          end      end     end  

But render json: @comment is returning the full object although in my CommentSerializer I have :

class CommentSerializer < ActiveModel::Serializer    attributes :id  end  

I am creating the new resource via ajax :

handleSubmit: function(e){          e.preventDefault();          $.ajax({              context: this,              method: 'POST',              url: "/questions/" + this.props.question_id + "/comments",              data: {comment: this.state},              success: function(data){                  this.props.handleNewComment(data);                  this.setState(this.getInitialState);              }          });        },  

What am I missing here?

How to find post URL in rails?

Posted: 18 Sep 2016 06:43 AM PDT

I'm trying to display the URL in rails but it returns an error

NoMethodError: undefined method `url' for #<Post:0x000000058ea918>  

What method can I use?

How to truncate n tables with one single ActiveRecord connection

Posted: 18 Sep 2016 05:47 AM PDT

I want to create a rake task in order to delete all records from a certain n number of tables and reset the values of the id column, so that when I create a new record it gets id 1.
Previous question Truncate table(s) with rails console is useful to get the job done for a single table (I would use delete_all in place of destroy_all if the task can be improved in performance):

Model.delete_all  ActiveRecord::Base.connection.execute("TRUNCATE #{table_name} RESTART IDENTITY")  

If I need to truncate more than one table, say tables table1, table2, table3, is there any chance to use a single ActiveRecord connection such as:

Model1.delete_all  Model2.delete_all  Model3.delete_all  ActiveRecord::Base.connection.execute("TRUNCATE #{table1, table2, table3} RESTART IDENTITY")  

and so avoid to establish multiple ActiveRecord connections like the example below?

Model1.delete_all  Model2.delete_all  Model3.delete_all  ActiveRecord::Base.connection.execute("TRUNCATE #{table1} RESTART IDENTITY")  ActiveRecord::Base.connection.execute("TRUNCATE #{table2} RESTART IDENTITY")  ActiveRecord::Base.connection.execute("TRUNCATE #{table3} RESTART IDENTITY")  

Unable to define relationship within ActiveRecord

Posted: 18 Sep 2016 05:38 AM PDT

I am trying to create an association between my attribute_set and attribute tables. Though ActiveRecord keeps displaying this error.

ArgumentError: You tried to define an association named attributes on the model AttributeSet, but this will conflict with a method attributes already defined by Active Record. Please choose a different association name.  

Jammit isn't adding a timestamp to my javascript files in Rails 2.3. How can I fix this?

Posted: 18 Sep 2016 05:06 AM PDT

Since jammit 0.4.4 :

"0.4.4  Jammit will now add the RAILS_ASSET_ID timestamp to image URLs within  your CSS packages, if configured, for better cache-busting. Greg Hazel  contributed a series of Jammit/Windows bug fixes."  

In my app, jammit doesn't add a timestamp in production mode, which makes it a fustrating to update the javascript in my app.

This is my config :

embed_assets: off  package_assets: on  compress_assets: off  rewrite_relative_paths: on  

This is how I use it :

<%= include_javascripts :normal %>  

and this is what it generates ;

<script src="/assets/normal.js"></script>  

Anyone any idea how I can fix my problem and add the timestamps? Thanks!

client-service architecture: keep client in sync with in-memory data sctructure

Posted: 18 Sep 2016 04:47 AM PDT

I have a service that updates a set in redis (fast in-memory data storage) in the real time. I also have a rails app that is connected to this redis instance. The task is to display the set contents to all the clients. Please note that according to some client's settings, some elements of the set are not supposed to be sent to them.

I don't want to send the whole set contents on every update. It should be possible to only send diff, and I'm choosing which approach to use.

implementation of rails -> client connection:

  • react - react sounds like a good fit for maintaining the real time state. If I make props updating in the real time, the html will be kept up to date for free.
  • actioncable - there is a component in newest rails that integrates websockets into rails app.

service -> redis set -> rails:

  • I could use pub/sub redis feature and make the service that writes to redis set send the elements that are changed/updated/deleted in the set, and then use the set itself only to send data to the new clients, and the existing ones will be kept in sync via pub/sub. So, to update a client, the following is performed:
    1. the service is about to update element in the set
    2. the service adds the element to the set in redis
    3. the service sends the element to the pub/sub queue
    4. rails app, being subscribed to the pub/sub queue, receives the element
    5. rails app filters the list of clients to see which ones should get the update (normally, it's most of them)
    6. rails app broadcasts the new item, and the clients render it

On top of that, I'll also have to implement change/delete cases. It seems like this approach is way too complex and low-level. Things can easily get out of sync, and they are duplicated in memory several times.

  • instead of pub/sub I can make rails app read redis set contents repeatedly and compute if any changes occured. It should be cheap as redis stores the set in memory. If rails app detects a change, it broadcasts it to the client. Still, it feels wrong to have to check if something has changed in memory based on a timeout.

Additional info: there will not be too many clients, maybe a thousand. The set will be updated once per second, sometimes more, sometimes less.

What will be the best approach to keep clients in sync with the state in redis? Is react usage justified? Is there some native react implementation of such "diff" pattern?

Error in allocating a connection. Cause: Class name is wrong or classpath is not set for : org.postgresql.ds.PGConnectionPoolDataSource

Posted: 18 Sep 2016 04:17 AM PDT

i am trying to connect my jruby on rails application with database using JNDI connection but i am getting error as "Error in allocating a connection. Cause: Class name is wrong or classpath is not set for : org.postgresql.ds.PGConnectionPoolDataSource" . i have already downloaded postgersql jdbc driver jar file named "postgresql-9.4.1210.jar" from site https://jdbc.postgresql.org/download.html and have placed this file in location /opt/glassfish4/glassfish/domains/domain1/lib but it is still not wokring..

Just for information my glassfish version is 4

what could be the reason for this??

Thanks,

How do I use devise sign in/up in a different view as a partial

Posted: 18 Sep 2016 04:30 AM PDT

I have my landing page which should contain and login form and a sign up form. I have two buttons of course once the user clicks on one of them it will render the appropriate form. I saw something like that on railscast. This is what I want to achieve

How do I use Rails Selectize in my Rails Project?

Posted: 18 Sep 2016 08:04 AM PDT

I'm getting the error

Selectize: Dependency MicroPlugin is missing    Make sure you either: (1) are using the "standalone" version of Selectize, or (2) require MicroPlugin before you load Selectize.  

application.js:

//= require jquery  //= require jquery_ujs  //= require selectize  //= require turbolinks  //= require bootstrap-sprockets  //= require jquery.validate  //= require jquery.validate.additional-methods  //= require_tree .  

Rails 4 Error: NoMethodError - undefined method

Posted: 18 Sep 2016 05:43 AM PDT

I am struggling ordering my loop through my Devise Users by the upvotes on tools created by them.

Inside of that loop I get the value I would like to use to order the elments with:

user.tools.map(&:cached_votes_up).sum  

That's my loop:

- @users.order(user.tools.map(&:cached_votes_up).sum).each do |user| #incorrect!  

And my controller:

@users = User.all  

Without order in my loop everything runs fine, with it this error appears:

NoMethodError in Users#index  Showing c:/Users/Jonas/gitapps/ocubit/app/views/users/index.html.haml where line #21 raised:    undefined method `tools' for #<Class:0xac2db78>  

I am grateful for each help!

Rails and Active Admin Nested Resources

Posted: 18 Sep 2016 03:56 AM PDT

I build a simple ecommerce app and i am using active admin for administration panel. My problem is this.

i have two models orders & order_items. order_items saves the orders products. The association is order -> has_many order_items & order_items -> belongs_to orders.

I have this code in active admin but i can't see the items of an order(blank).

 index :title => 'orders' do    selectable_column    id_column    column "value", :subtotal    column "tax", :tax    column "shipping", :shipping    column "total value", :total    column "status", :order_status_id     column "created_at", :created_at     column "updated_at", :updated_at    column "order_items", :order_items    actions  end  

I can reach order_items throw console so there is no problem with the model associations.

Rails models : SQL OR AND keywords

Posted: 18 Sep 2016 08:08 AM PDT

I use rails and I want a request likes that:

SELECT * FROM events WHERE id = 5 AND   active = true AND   (current_state = 0 OR current_state = 1)  

I write something likes that:

Event.where(id:5).where(active:true).or(Event.where(current_state:)).or  (Event.where(current_state: 1))  

But when I do that, I have this request:

SELECT * FROM events WHERE id = 5 AND   active = true AND   current_state = 0 OR current_state = 1  

How can I have parentheses?

How to upload privatekey.pem to aws and use url as path in controller

Posted: 18 Sep 2016 02:51 AM PDT

Maybe this is possible or not. So far I have two ways:

1: Upload to AWS (encrypted) 2: Upload to local server

The API I use requires the user to use their privatekey.pem that they generated. I use React to upload that file to AWS but the error I got, when linking to the uploaded url is:

Errno::ENOENT (No such file or directory @ rb_sysopen - https://s3.amazonaws.com/......

In short pieces:

React for upload:

...    // Got this from an old project that upload images  _privateKeyUrl(e){    var file = this.refs.file.files[0];    var reader = new FileReader();    var url = reader.readAsDataURL(file);    reader.onloadend = function (e) {      this.setState({          privateKeyUrl: [reader.result], preview: true      })    }.bind(this);  }    _onSave(){    /*    * Do not use .serialize()!    * It's not a good idea if we want to send a form with post method    * But instead:    */    var fd = $(this.refs.myForm).context;    var formData = new FormData(fd);      $.ajax({      url: '/settings/save',      type: 'POST',      data: formData,      cache: false,      contentType: false,      processData: false,      success: function (data, xhr) {          console.log("success")        }.bind(this),      error: function (data) {          console.log("error")      }    });  }    //Render    <form ref="myForm" encType="multipart/form-data">    <input ref="file" type="file" multiple="false" onChange={this._privateKeyUrl}/>    <input type="hidden" name="setting[private_key_url]" value={this.state.privateKeyUrl} multiple="false" />  </form>  <button onClick={this._onSave.bind(this)}>Save</button>    ...  

Paperclip initializer:

Paperclip.options[:content_type_mappings] = {    pem: ['text/plain', 'application/x-x509-ca-cert']  }  

Model:

class Setting < ApplicationRecord    belongs_to :shop    # https://github.com/thoughtbot/paperclip/wiki/Encryption-on-amazon-s3    has_attached_file :private_key_url, s3_permissions: :private,                                        storage: :s3,                                        s3_region: 'us-west-2',                                        s3_server_side_encryption: "AES256",                                        s3_credentials: Proc.new{|a| a.instance.s3_credentials}      validates_attachment_content_type :private_key_url, content_type: ['text/plain','application/x-x509-ca-cert'] # see paperclip.rb in initializer      def s3_credentials      {:bucket => ENV['S3_BUCKET_NAME'], :access_key_id => ENV['AMAZON_ACCESS_KEY_ID'], :secret_access_key => ENV['AMAZON_SECRET_ACCESS_KEY']}    end  end  

Controller:

...    def api    My::API.new(<consumer_key>, <secret>, Shop.first.setting.private_key_url.url)  end    ...  

If the file was at the root of the server then all is well. Would it be best to have the user upload the file to my server instead? Can I upload pem files to AWS and link that as a path in my controller?

group by day based on a particular column with its unique entries - ROR

Posted: 18 Sep 2016 04:40 AM PDT

I have two tables ImportedContactUser and ImportedContact and the former contains a column imported_contact_id.

Now, there are many entries for the same imported_contact_id in the first table. What i want to do is to group the unique imported_contact_id entries by day.

I am able to group the unique entries by day but the challenge comes when some entries which was imported yesterday are being imported today also by some other user, in that case same entries are being counted for yesterday and today when i group it by day. So, what I'm trying to do is

  1. first get the unique entries till date
  2. then apply group by day on it

So that I will have only unique entries count on grouping by each day. But with this also I'm not having any luck.

Below are the images of my two tables:

First image is for 'ImportedContactUser' table

Second one is for 'ImportedContact' table

Current code for retrieving the data:

ImportedContactUser.where("platform_id = 6 and updated_at > ? and updated_at <= ?", DateTime.new(2016, 6, 1), Date.today.at_end_of_day).select("DISTINCT imported_contact_id").group("date_format(updated_at, '%Y-%m-%d')").count  

Rails - No proper access to self join model

Posted: 18 Sep 2016 08:12 AM PDT

I have model called Section, and I want section to be able to have many Sections - so a Self Joins seems like a place to start.

I setup my code like this:

Model file

class Section < ApplicationRecord      belongs_to :offer      has_many :offer_items        # Self joins:      has_many :child_sections, class_name: "Section", foreign_key: "parent_id"      belongs_to :parent_section, class_name: "Section", optional: true  end  

Migration file

class CreateSections < ActiveRecord::Migration[5.0]    def change      create_table :sections do |t|        t.string :name        t.references :offer, foreign_key: true          t.references :parent_section, foreign_key: true        t.timestamps      end    end  end  

As you can see I set belongs_to :parent_section as optional, as no every section should has its parent.

When I print attribute_names of my Section model it says:

=> ["id", "name", "offer_id", "parent_section_id", "created_at", "updated_at"]  

Trying to retrieve child_sections gets me an error:

ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: sections.parent_id: SELECT "sections".* FROM "sections" WHERE "sections"."parent_id" = ?  

Where did I make my mistake?

How to set morris.js values from Rails controller

Posted: 18 Sep 2016 08:11 AM PDT

I struggle with adding circle graph in my sport app. Is it possible to set morris.js value to variable from my controller? I have @diet_calories variable in controller and I want to display Carbs -> Protein -> Fat in 60% -> 20% -> 20% relation. If I set value of carbs in script tag (value: @diet_calories * 0.6) it dosn't work. Do you have some suggestions to fix that?

application.html.erb :

<script>      new Morris.Donut({           element: 'diet-circle',           data: [             { label: "Carbs", value: @diet_calories * 0.6 },             { label: "Protein", value: @diet_calories * 0.2 },             { label: "Fat", value: @diet_calories * 0.2 }           ]      });  </script>  

info_controller.rb :

def diet      if current_user.activity == "Sedentary"          if current_user.goals == "Lose Weight"              @diet_calories = ((@bmr * 1.1) - 300).to_i          elsif current_user.goals == "Maintain Weight"              @diet_calories = (@bmr * 1.1).to_i          elsif current_user.goals == "Add some weight"              @diet_calories = ((@bmr * 1.1) + 300).to_i          end      elsif current_user.activity == "Low"          if current_user.goals == "Lose Weight"              @diet_calories = ((@bmr * 1.5) - 300).to_i          elsif current_user.goals == "Maintain Weight"              @diet_calories = (@bmr * 1.5).to_i          elsif current_user.goals == "Add some weight"              @diet_calories = ((@bmr * 1.5) + 300).to_i          end      elsif current_user.activity == "Medium"          if current_user.goals == "Lose Weight"              @diet_calories = ((@bmr * 1.7) - 300).to_i          elsif current_user.goals == "Maintain Weight"              @diet_calories = (@bmr * 1.7).to_i          elsif current_user.goals == "Add some weight"              @diet_calories = ((@bmr * 1.7) + 300).to_i          end      elsif current_user.activity == "High"          if current_user.goals == "Lose Weight"              @diet_calories = ((@bmr * 2.1) - 300).to_i          elsif current_user.goals == "Maintain Weight"              @diet_calories = (@bmr * 2.1).to_i          elsif current_user.goals == "Add some weight"              @diet_calories = ((@bmr * 2.1) + 300).to_i          end      end  

diet.html.erb :

<div id="diet-circle"></div>  

Rails installation Error: dyld: lazy symbol binding failed: Symbol not found: _clock_gettime

Posted: 18 Sep 2016 02:13 AM PDT

i am trying to "rvm install 2.3.0" and coming up with the following error:

ruby-2.3.0 - #extracting ruby-2.3.0 to /Users/MyDocs/.rvm/src/ruby-  2.3.0....  ruby-2.3.0 -  #configuring......................................................|  ruby-2.3.0 - #post-configuration.  ruby-2.3.0 - #compiling...........  Error running '__rvm_make -j 1',  showing last 15 lines of /Users/MyDocs/.rvm/log/1474189145_ruby-   2.3.0/make.log  compiling ./missing/explicit_bzero.c  compiling ./missing/setproctitle.c  compiling dmyenc.c  linking miniruby  config.status: creating ruby-runner.c  dyld: lazy symbol binding failed: Symbol not found: _clock_gettime  Referenced from: /Users/MyDocs/.rvm/src/ruby-2.3.0/./miniruby (which   was built for Mac OS X 10.12)  Expected in: /usr/lib/libSystem.B.dylib    dyld: Symbol not found: _clock_gettime  Referenced from: /Users/MyDocs/.rvm/src/ruby-2.3.0/./miniruby (which   was built for Mac OS X 10.12)  Expected in: /usr/lib/libSystem.B.dylib    make: *** [.rbconfig.time] Trace/BPT trap: 5  ++ return 2  There has been an error while running make. Halting the installation.  Davids-MBP:~ MyDocs$   

I've been stuck on this for a while and really not getting anywhere...

if else if else in angular js

Posted: 18 Sep 2016 03:33 AM PDT

I have to incorporate angular in my slim file, I'm not sure how to transform if else block in angular. I know angular don't have ng if else statements but is there a way to change below code to angular

- if @cart['empty']      cart is empty  - elsif @cart['invalid']     can't proceed  - else    -@cart['Items'].each do |item|        #{item['description']}  

I want to achieve some thing like this

  ng-if="cart.empty"       cart is empty      ng-else-if cart.invalid       can't proceed      ng-else       ng-repeat="cart.Items as item"            item.description  

How to test and deploy a Docker production image?

Posted: 18 Sep 2016 02:39 AM PDT

I'm developing on Ruby on Rails and start using Docker for deployment for a month.

The following are the steps I'm working on.

  1. dev on my laptop
  2. push to gitlab
  3. build a single image including test and production gems
  4. run rspec against this image
  5. (pass)push to registry, (fail) discard image

With this workflow, I will have a single image that have all testing, development and production gems.

The workflow that I find from talking with many people

  1. dev on my lap top
  2. push to gitlab
  3. build test image (all gems necessary for testing)
  4. run rspec against test image
  5. (pass)build another image for deployment without test gems and push to docker registry, (fail)discard the image

With this method, I think it's violating the purpose of Docker (the image that being test should be indifference from the one that will be deploy).

How to specify and implement an approach that test and push a production image?

Rspec forward and back slash

Posted: 18 Sep 2016 01:57 AM PDT

I saw this line of code in betterspecs.

it { expect(assigns('message')).to match /it was born in Belville/ }  

What does the slashes before 'it' and after 'Belville' mean?

bundle does not respect gemrc?

Posted: 18 Sep 2016 01:32 AM PDT

I've configured gem source with gem command, now gem rc is like

---  :backtrace: false  :bulk_threshold: 1000  :sources:  - http://rubygems.org/  :update_sources: true  :verbose: true  

However when I run bundle install it still fetches from https://rubygems.org,

How can I change it to http scheme too?

P.S https is slow in my local network, so I need to use http connection instead.

Turbolink causing issue to load the 3rd party javascript(zendesk) on next page

Posted: 18 Sep 2016 01:43 AM PDT

I am on rails3, and Turbo-links causes the link for zendesk to not work.

I was using zendesk script and that was not loading on next page and then I have used script that mentioned here. It seems working fine on chrome, but on Firefox and Safari, its still causing problem.

I have included below lines into my layout:

= javascript_include_tag 'zendesk', 'data-turbolinks-track' => true    :javascript    document.addEventListener('page:change', zendesk_web_widget());    and zendesk_web_widget() is function that loading widget.  

I have searched around web and found some solutions but not working at all:

Rails 4 turbo-link prevents jQuery scripts from working

https://github.com/turbolinks/turbolinks-classic/issues/166

Any anyone has any idea then please let me know.

No comments:

Post a Comment