Saturday, December 24, 2016

Rails - Docker Your Ruby version is 2.3.1, but your Gemfile specified 2.2.3 | Fixed issues

Rails - Docker Your Ruby version is 2.3.1, but your Gemfile specified 2.2.3 | Fixed issues


Rails - Docker Your Ruby version is 2.3.1, but your Gemfile specified 2.2.3

Posted: 24 Dec 2016 07:46 AM PST

I have sample ROR application( ruby 2.2.3 and rails 4.2.6 ) with Dockerfile

FROM ruby:2.2.3  FROM rails:4.2.6  ENV INSTALL_PATH /home/projects/sample_ror_files  RUN mkdir -p $INSTALL_PATH  WORKDIR $INSTALL_PATH  ADD Gemfile /home/projects/sample_ror_files/Gemfile  ADD Gemfile.lock /home/projects/sample_ror_files/Gemfile.lock  RUN bundle install  COPY . $INSTALL_PATH  EXPOSE 3000  CMD ["rails", "server", "-b", "0.0.0.0"]  

When I try to docker build -t test_image . I am getting following error message.

Your Ruby version is 2.3.1, but your Gemfile specified 2.2.3 The command '/bin/sh -c bundle install' returned a non-zero code: 18

I have installed many ruby version in my system but currently choosen 2.2.3 and I am also getting 2.2.3 when run ruby -v

I am not sure what was the issue...

Storing chart data in database

Posted: 24 Dec 2016 07:06 AM PST

I have a web app (Rails) that I want to use to create chart. For now what I do is :

  • Upload the file containing my data to display
  • Store this file and associate it to a model Sample
  • When I want to view this Sample I extract the data from the file previously uploaded and create the chart using ChartJS

But I don't really like this solution because the charts are recreated every time, and most of all I want to be able to do some statistics over the time on my charts data and if I keep them into file, it's difficult...

Each sample is about ~1000 rows, so it seems "not conventional" to store 1000 new rows every time I create a sample ?


Today I have :

Sample  ..... id : int  ..... attachment : txt file containing the data  

Is it OK to change it to :

Sample  ..... id : int  ..... attachment : txt file containing the data  ..... chart_data_id : associated ChartData    ChartData  ..... id : int  ..... x : int  ..... y : int  

I hope I'm clear with my explanations... For example, in my database I would have one Sample whiwh has_many ChartData :

Sample(id: 1, attachment: my_file, chart_id: 10)    ChartData(id: 10, x: 0, y: 1)  ChartData(id: 10, x: 3, y: 2)  ChartData(id: 10, x: 5, y: 7)  .....  

Thanks

Ruby Rails Average two attributes in a query returning multiple objects

Posted: 24 Dec 2016 07:21 AM PST

I've got two attributes I'm trying to average, but it's only averaging the second field here. is there a way to do this?

 e = TiEntry.where('ext_trlid = ? AND mat_pidtc = ?', a.trlid, a.pidtc).average(:mat_mppss_rprcp && :mat_fppss_rprcp)  

Why can't I upload a file larger than 1MB to S3 with carrierwave and fog-aws?

Posted: 24 Dec 2016 06:56 AM PST

I have implemented a file upload for my rails app using carrierwave, S3 and fog-aws. It works well in my local development environment regardless of file size. But when deployed to AWS, file uploads < 1MB succeed, anything > 1MB has resulted in a ERR_CONNECTION_RESET in Chrome and 'The connection was reset' in Firefox.

The following is the gems I used.

gem 'carrierwave', '~> 1.0'  gem 'fog-aws', '~> 1.1'  

The following is my carrierwave.rb

CarrierWave.configure do |config|    config.fog_provider = 'fog/aws'    config.fog_credentials = {        provider: "AWS",        aws_access_key_id: ENV["S3_KEY"],        aws_secret_access_key: ENV["S3_SECRET"],        region: ENV["S3_REGION"]      }    config.fog_directory = ENV["S3_BUCKET"]  end  

The following is my uploader.

class AttachmentUploader < CarrierWave::Uploader::Base    storage :fog      def store_dir      "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"    end  end  

text classification predefined categories with documents with Omnicat-bayes

Posted: 24 Dec 2016 06:35 AM PST

I'm using omnicat-bayes to analyse documents (text-classification). With this gem I'm able to create categories and "feed" those with documents. Currently the categories have enough documents in order to be "good enough" to recognize new documents in what category they should be placed in.

Now in my Documents controller under the create action are a few steps.

  1. Creating a new Bayes instance
  2. Creating the categories that will be used
  3. Taking the pre-documents to train the categories
  4. Actually training the categories

(all of those steps are under the run_all function)

The create action:

def create  @document = Document.new(document_params)  @document.case_id = @case.id   if @document.save     run_all     # Running the classify function on reden aanmelding     classify_one = @bayes.classify(@document.reden_aanmelding)     document_category = classify_one.to_hash[:top_score_key]     # Updating the document category by the top key returned by Bayes     @document.update_attribute(:category, document_category)     finding_required_records     # Training Cees Buddy with the document that got saved     @bayes.train(document_category, @document.reden_aanmelding)     redirect_to case_path(@case)   else     render :new   end  end  

Inside the @document.save run_all function (I know this isn't really best practice) I'm creating the four steps named above.

Now after the create function is finished the Bayes instance is gone and the AI is now "stupid" again so to speak.

My question is: what would a proper place be and how can I accomplish this to create the new instance, new categories and feed them with documents out of my database. Would a singleton be interesting here?

wickedpdf not rendering images in local and amazon aws in rails?

Posted: 24 Dec 2016 07:26 AM PST

i am using wickedpdf gem to generate pdf invoice from the html code.

gems:

gem 'wicked_pdf'  gem "wkhtmltopdf-binary"  

gemfile.lock

wicked_pdf (1.0.6)  wkhtmltopdf-binary (0.9.9.3)  

in controller:

  def show_pdf_invoice      respond_to do |format|        format.html { render :layout => "pdf.pdf.erb" }        format.pdf do      render pdf: "show_pdf_invoice", :layout => 'pdf.pdf.erb'      #render :pdf => "pdf"#, :layout => 'pdf.html.erb'        end      end    end  

in views/invoices/show_pdf_invoice.pdf.erb

  <img id="image" src="https://www.google.co.in/logos/doodles/2016/holidays-2016-day-2-6356741311692800-scta.png" alt="logo" />     <%= wicked_pdf_image_tag 'https://www.google.co.in/logos/doodles/2016/holidays-2016-day-2-6356741311692800-scta.png' %>  

pdf is getting generated. But the images are not showing. in the place of images empty boxes are coming. unable to find the issue.

Travis CI "An error occurred while installing rack (2.0.1), and Bundler cannot continue."

Posted: 24 Dec 2016 05:38 AM PST

I have an error in Travis CI:

"An error occurred while installing rack (2.0.1), and Bundler cannot continue."  

I tried to update racks but I didn't help. Ruby ver: ruby 2.2.4.p230 Does anyone know how to fix it?

How to use usermodel from mainApp in custom engine

Posted: 24 Dec 2016 06:28 AM PST

I've created an RoR-App and I want to add a simple blog as engine that is already mountet to /blog where users can have their own blog. Now I didn't find anything how I can use the model user.rb in my blog engine.

In my main app I can use current_user.username but in my engine I can't use it.

EmberJs Data Goes Null to Server

Posted: 24 Dec 2016 05:20 AM PST

I am building a toy app and wanted to work with a simple 1:many relationship. My car model "hasMany comments" & my comments "belongsTo car".I want a comment to be created from cars/car route.So i didn't created a route for comments/new.For a quick trial i have added a button that has "saveComment" action.

<button type="submit" {{action 'saveComment' model}}>Submit</button>  

!!! I am passing the model(which refers to current Car object) because in my action i want to read it's id and set it to comments car_id.

And here is the correspanding route file

  model(params){     return this.store.findRecord('car', params.car_id);    },   actions: {    saveComment(model){       let car = this.store.peekRecord('car', model.id),       let newComment = this.store.createRecord('comment'{              car: car,              body: 'Some filler text! ',          });     car.get('comments').pushObject('newComment');     newComment.save();    }  

The problem is, my (let the route be cars/10) current template includes the newly generated comment with the proper body, however when i inspect it, belongsTo relationship looks empty.Since car_id goes null, after a reload, new generated comments disappeares.(not from the database tho, it is saved succesfully without a car relationship).What should i do to get this comments.car saved? TIA

Rails - render :layout => false on new action

Posted: 24 Dec 2016 05:23 AM PST

I am using render :layout => false for my new action.

All works fine, until I submit the form with validation errors. The create action calls render :new and I see the form, with the bullets outlining the errors. The issue is that the form now renders with application layout and seems to be ignoring the render :layout => false.

From what I can tell I believe this is because I am not actually redirecting to :new, just rendering the :new view whilst still in the create action. I cant add render :layout => false to the create action, because rails only allows one render per action.

Is there a way to get the form with validation errors to not use the application layout? I still want the bullets with the validation errors.

Why is initializing variables so important?

Posted: 24 Dec 2016 06:31 AM PST

Please can someone explain to me, why NOT initializing first_idx and last_idx causes the code not to run??

When I run it I get this error "undefined local variable or method last_idx". I know that the advice is to always initialize the variables, but I don't understand why. After all first_idx and last_idx will ALWAYS get a value inside the loop because the argument letter is always present in the string (in this particular problem).

I'd really appreciate some (simple) insight. Thank you!

P.S, I also know that the problem is easily solved using #index and #rindex in Ruby, but I'm not allowed to solve it using straightforward methods.

def find_for_letter(string, letter)    first_idx = nil  0.upto(string.length - 1) do |idx1|      if string[idx1] == letter          first_idx = idx1          break      end  end    last_idx = nil  (string.length - 1).downto(0) do |idx2|      if string[idx2] == letter          last_idx = idx2          break      end  end    if last_idx == first_idx      return [first_idx]  else      return [first_idx, last_idx]  end  end        def first_last_indices(word)      h = {}      word.chars.each do |char|          h[char] = find_for_letter(word, char)      end      h  end  

AWS EC2 Default Ruby Version on Login

Posted: 24 Dec 2016 05:13 AM PST

so I have my rails project hosted with AWS EC2 using the amazon linux server. by default, ruby -v returns ruby 2.0 but my project was designed on 2.3.3 (latest at the time). in order for me to change the ruby version using rbenv i have to run the following every time i log in via ssh

$ echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bash_profile  $ ~/.rbenv/bin/rbenv init  $ source ~/.bash_profile  $ eval "$(rbenv init -)"  $ type rbenv  

since i have the global ruby version in rbenv set as 2.3.3 already. then i can run

$ ruby -v  #returns 2.3.3  $ rails s  #or any other rails commands  

is there any way I can set it so I don't have to edit the .bash_profile every time?

How to add a JSON column in MySQL with Rails 5 Migration

Posted: 24 Dec 2016 04:52 AM PST

I'm trying to add a json column in MySQL db by running:

class AddStatisticsToPlayerStatistic < ActiveRecord::Migration[5.0]      def change         add_column :player_statistics, :statistics, :json      end  end  

But I'm getting this error when I try to run rake db:migrate

Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'json' at line 1: ALTER TABLE `player_statistics` ADD `statistics` json  

Does anyone know how to add a JSON column in MySQL Ver 14.14 Distrib 5.5.53. properly?

Thanks in advance!

websocket-rails API endpoint accessed through browser causes app to break

Posted: 24 Dec 2016 04:09 AM PST

I'm using websocket-rails to provide an API endpoint for a JS client, which works great, but I've been struggling to solve something which causes the app to cease working until I restart puma.

If the API endpoint /websocket is visited through the browser, it causes the the following error: RuntimeError: async response must have empty headers and body, and then when the JS client attempts to connect normally, it fails instantly, yielding: RuntimeError (eventmachine not initialized: evma_install_oneshot_timer)

Is there any way I can prevent a "normal" GET request to /websocket?

I should say, I have no idea why the endpoint is being visited through the browser (or effectively so).

Thanks in advance.

Routing errors in rails

Posted: 24 Dec 2016 07:36 AM PST

How to make this error go ?

No route matches [POST] "/controller/controller id/controller/new".

Controller:

POST /doctors

POST /doctors.json

def create @doctor = Doctor.new(doctor_params)

respond_to do |format|    if @doctor.save    format.html { redirect_to @doctor, notice: 'Doctor was successfully created.' }    format.json { render :show, status: :created, location: @doctor }    else    format.html { render :new }    format.json { render json: @doctor.errors,status::      unprocessable_entity }    end  end  

end

Rails Single Table Inheritance with dynamically defined classes

Posted: 24 Dec 2016 03:24 AM PST

In using Rails STI (Single Table Inheritance), I have defined a model named Poi (point of interest).

Our app's requirement dictate that subclasses of Poi (like Restaurant, Club, etc) must be created in an Admin::Categories view (where it has a class_name string input field), so that an Admin should be able to create a new subclass at anytime without needing a programmer to open a new ruby file with an empty (useless) subclass and re-deploy the app.

At the same time, IF in the future we want to specify different behavior (either instance/class methods) for a subclass of Poi, we can just create that ruby file, but that should be an option and not mandatory. The same goes for a different form with different fields for that subclass: we just need to setup a partial_name_for_form instance method in that subclass that returns a string with the partial name and the views will render that accordingly. If none is found, the default Poi views are rendered.

Since Rails raises an error if you try to instanciate a new Poi object with 'type' attribute that doesn't match a subclass of Poi (so the subclass MUST be previously defined), we came up with the following solution for dynamically creating the Poi subclasses based on class_name:

  1. An after_create hook in model Category that defines the new class immediately using this code: Object.const_set(category.class_name, Class.new(Poi))

  2. A require_dependency call in model Poi file (because it's in the autoload path) to require the ruby files for the subclasses we have eventually created hardcoded subclasses (only if the file exists):

Category.all.each do |category|

require_dependency category.class_name.underscore if File.exist (File.join("app","models","pois","#{category.class_name.underscore}.rb"))

end

  1. An initializer that defines all remaining classes (by 'remaining' I mean other subclasses that don't still have their own ruby file defining them) using the same code in #1, but checking if Object.const_defined? category.class_name first (because the ones defined by require_dependency don't need to be re-defined).

Even tough all this complexity made we almost regret using STI in the first place, it was working fine - in development.

But in production environment, after the creation of a new category providing class_name, the Class doesn't get defined, because when trying to create a new Poi with that subclass is raising an error uninitialized constant.

I confirmed in Rails console in Production environment that the after_create hook IS working, because the class is being defined there. My wild guess is that because we use Unicorn, this bug could be related to the forking of the application code, but I have no clue how to proceed.

displaying info from db with rails doesn't work

Posted: 24 Dec 2016 03:06 AM PST

I'm actually working on a simple rails app. I generated a Rails g scaffold Course.

Picture of folders generated by the scaffold

Now i want to display all the courses that i create, with a title, a picture and a short description. here is the code to do it

<p id="notice"><%= notice %></p>  <h1>Courses</h1>  <div class="row">  <% @courses.each do |course| %>        <div class="col-sm-6 col-md-4 col-lg-3">          <div class="thumbnail">            <td><%= link_to 'Show', course %></td>            <td><%= link_to 'Edit', edit_course_path(course) %></td>            <td><%= link_to 'Destroy', course, method: :delete, data: { confirm: 'Are you sure?' } %></td>            <%= image_tag( course.image, width: 250, height: 250) %>            <div class="caption">              <h3><% course.title %></h3>              <p><% course.description %></p>              <%= link_to 'that course', course_path(course), class:"btn btn-default"%>            </div>          </div>        </div>      <% end %>      </div>  <%= link_to 'New Course', new_course_path %>  

With this, the picture is displayed, but not the title and the description neither Html is made by rails to make the title and the description, but it stay empty. Source code

I suppose that i made a mistake somewhere but i can't figure it out.

ps: I checked with the rails console, the title and the description exist in my database

Thx for your help

Heroku error due to an already removed folder

Posted: 24 Dec 2016 03:03 AM PST

I am trying to deploy Heroku but I still have same error:

    rake aborted!      remote:        Sass::SyntaxError: Invalid CSS after ".../sass-lang.com/": expected "{", was ""  remote:        /tmp/build_fa42ee7d4fc8aec796bb9d2efab757a3/app/assets/stylesheets/todo_tasks.scss:4  

I have removed todo_tasks.scss, it is no longer in the app on github but still I have this error, I tried even installing heroku one more time ^^

What should I do?

Can't update a gist immediately after creating it

Posted: 24 Dec 2016 02:34 AM PST

I am trying to use the gist API as a adhoc diff tool. To do this I want to upload some text to a gist and then update it and view the diff. For some reason I am getting "{\"message\":\"Not Found\",\"documentation_url\":\"https://developer.github.com/v3\"}" as a result. Its slightly confusing as when I view the url I can see the GIST fine.

My code is as follows

uri = URI("https://api.github.com/gists")    first_payload = {      'description' => "My test gist",      'public' => true,      'files' => {          'change.yml' => {              'content' => "before"          }      }  }    req = Net::HTTP::Post.new(uri.path)  req.body = first_payload.to_json  req.basic_auth("username", "password")  res = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => true) do |http|    http.request(req)  end    second_uri = URI(JSON.parse(res.body)["url"])  second_payload = {      'description' => "My test gist",      'public' => true,      'files' => {          'change.yml' => {              'content' => ':after'          }      }  }    second_req = Net::HTTP::Put.new(second_uri.path)  second_req.body = second_payload.to_json  second_req.basic_auth("username", "password")  second_res = Net::HTTP.start(second_uri.hostname, second_uri.port, :use_ssl => true) do |http|    http.request(second_req)  end  

prawn bounding box get remaining height

Posted: 24 Dec 2016 03:21 AM PST

I have been following this stack answer for content overflow, Controlling content flow with Prawn from one column to another, The problem i face is, i cannot get the current position of the cursor inside the bounding box. So that i could do calculation to get the remaining height in bounding box and set it to the next text box, currently it overflows the bounding box.

bounding_box([175, starting_y - 240], :width => 30.mm, :height => 67.5.mm) do    transparent(1) { stroke_bounds }    indent 5,5 do       column_box([0, cursor], columns: 1, width: bounds.width) do        text "#{cursor}"        text "XS", align: :center, inline_format: :true        text "XS", align: :center, inline_format: :true        text 'XS', align: :center, inline_format: :true        text 'aaaa', align: :left        text "<b> asda </b>: #{sec_call}", inline_format: true      end      column_box([0, cursor], columns: 5, width: bounds.width, height: 0.27.cm) do        image open('https://image.freepik.com/icones-gratis/t-shirt-no-cabide_318-84568.png'), width: 0.27.cm        image open('https://image.freepik.com/icones-gratis/t-shirt-no-cabide_318-84568.png'), width: 0.27.cm      end      column_box([0, cursor], columns: 1, width: bounds.width) do        text "#{care_instr.upcase}"        text "#{imported_for}"        text "CA 17897"        text "FABRIQUE EN CHINE/ HECHO EN"        text "CHINA"      end      # span(bounds.width, position: :left) do      #   text_box "#{care_instr.upcase}", at: [180, cursor], overflow: :truncate, :width => 25.mm      #   text_box "#{imported_for}", at: [180, cursor-45], overflow: :truncate, :width => 25.mm      # end      span(bounds.width, position: :left) do        text_to_write = text_box text_to_write, at: [180, cursor], overflow: :truncate, :width => 25.mm, :height => 50.5.mm      end    end  end  

text_to_write is a long text which needs to be carried to next column which is working fine, sometimes the "#{sec_call}" value increaes so the text to write overlaps/overflows the table, so i need to dynamically change the height so it flows correctly to next column.

Whenever i print cursor inside bounding box it says 0.0, the bounding box height is static and its position also is there any way to calculate the remaining space inside bounding box from current position

Rails simple form saving twice the input attributes of the Object

Posted: 24 Dec 2016 02:25 AM PST

I'm trying to prevent rails from showing twice the comments and I presume that is because I'm using the .build and create methods one in the partial form (the build one) and the other in the Comments controller. But I don't know how to solve it.

So in the /views/comments/_form.html.erb:

<%= simple_form_for([@pic, @pic.comments.build]) do |c| %>      <%= c.input :comment %>  <%= c.button :submit, class: "btn-custom2" %>      <% end %>

And in the CommentsController:

class CommentsController < ApplicationController  	before_action :find_comment    	def new  		  		@comment= Comment.new  		  	end  	def create  		  		@comment= Comment.new(comment_params)  		@comment.picture_id= @pic.id  		@comment.user_id= current_user.id    		if @comment.save  			redirect_to picture_path(@pic)  			# @pic is the id that is needed in order to access the picture_path  			# then, in the view of picture show I could see the pictures which is stored in the db by:  			# <% current_user.pictures.find(@pic.id).comments.each do |comment| %>  			# <%= comment.comment %>  			# <% end %>  		else  			render "new"  			# by rendering here the page doesn't refresh so the input of the comments   			# that we were putting we won't lose, whereas with redirect_to yes  			  		end  	end      	private    	def comment_params  		params.require(:comment).permit(:comment)  	end  	def find_comment  		@pic= Picture.find(params[:picture_id])  		  	end  end

Rails collection_check_boxes with Main type as well it's subtypes

Posted: 24 Dec 2016 03:20 AM PST

Iam Working on an Event Management System, where i have HABTM between events and employees, I have created a checkbox with employees name like this,

<%= f.collection_check_boxes :employee_ids, Employee.all, :id,           :emp_name do |e| %>         <div class="collection-check-box-subtypes">         <%= e.check_box %>             <%= e.label %>         </div>  <%end%>    

but there are so many employees, therefore i want my employees to be selected by their department as well, so that it becomes more easy to select employees by departments rather than indiviually. And i also want to keep select all checkbox which is working right now perfectly. Therefore in short i want to create a checkbox like selectall/deselect all, than below the department name checkbox and under department the employees of that departments. Iam currently displaying the checkbox in front of the name of the departments, but it is not working as i want, below is the code: Select/Deselect All

  <% @employees.each do |department, employee|%>    <input type="checkbox" name="" value="selectDepartment" id="selectDepartment">      <label for="selectDepartment">        <%= department.name%>      </label><br>        <div class="field">          <div class="sub_check_box">            <%= f.collection_check_boxes :employee_ids, employee, :id, :emp_name do |e| %>                <div class="collection-check-box-subtypes">                  <%= e.check_box %>                  <%= e.label %>                </div>            <%end%>            </div>        </div>    <%end%>  

Please if anyone can help me.

RubyMine debugger error locked to rake

Posted: 24 Dec 2016 01:36 AM PST

When I started debugger have error and dont understand what need to do for fix this

Fast Debugger (ruby-debug-ide 0.6.0, debase 0.2.1, file filtering is supported) listens on 0.0.0.0:51898  Uncaught exception: Your bundle is locked to rake (12.0.0), but that version could not be found in any of the sources listed in your Gemfile. If you haven't changed sources, that means the author of rake (12.0.0) has removed it. You'll need to update your bundle to a different version of rake (12.0.0) that hasn't been removed in order to install.  

Why bunble is locked? I run bundle update, but not help

I go to run -> edit configurate go to button bundler and clik run the script in context of the bundle

and still have error when run shift + F9 for my test file

/home/ivan/.rvm/rubies/ruby-2.3.3/bin/ruby -e at_exit{sleep(1)};$stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift) /home/ivan/.rvm/gems/ruby-2.3.3/gems/ruby-debug-ide-0.6.0/bin/rdebug-ide --disable-int-handler --evaluation-timeout 10 --rubymine-protocol-extensions --port 52425 --host 0.0.0.0 --dispatcher-port 53157 -- /home/ivan/host/courses/lesson8/bin/rails test  Testing started at 10:57 ...  /home/ivan/.rvm/gems/ruby-2.3.3/gems/bundler-1.13.6/lib/bundler/definition.rb:179:in `rescue in specs': Your bundle is locked to sprockets (3.7.1), but that version could not be found in any of the sources listed in your Gemfile. If you haven't changed sources, that means the author of sprockets (3.7.1) has removed it. You'll need to update your bundle to a different version of sprockets (3.7.1) that hasn't been removed in order to install. (Bundler::GemNotFound)  from /home/ivan/.rvm/gems/ruby-2.3.3/gems/bundler-1.13.6/lib/bundler/definition.rb:173:in `specs'  from /home/ivan/.rvm/gems/ruby-2.3.3/gems/bundler-1.13.6/lib/bundler/definition.rb:233:in `specs_for'  from /home/ivan/.rvm/gems/ruby-2.3.3/gems/bundler-1.13.6/lib/bundler/definition.rb:222:in `requested_specs'  from /home/ivan/.rvm/gems/ruby-2.3.3/gems/bundler-1.13.6/lib/bundler/runtime.rb:118:in `block in definition_method'  from /home/ivan/.rvm/gems/ruby-2.3.3/gems/bundler-1.13.6/lib/bundler/runtime.rb:19:in `setup'  from /home/ivan/.rvm/gems/ruby-2.3.3/gems/bundler-1.13.6/lib/bundler.rb:99:in `setup'  from /home/ivan/.rvm/gems/ruby-2.3.3/gems/bundler-1.13.6/lib/bundler/setup.rb:20:in `<top (required)>'  from /home/ivan/.rvm/rubies/ruby-2.3.3/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'  from /home/ivan/.rvm/rubies/ruby-2.3.3/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'  

Process finished with exit code 1

look small different not like previus error but still I dont can debugger what mine - Your bundle is locked to sprockets (3.7.1) ?

I restart RubyMine but still have error, look screen_error

Include Wallet One middleware rails

Posted: 24 Dec 2016 01:28 AM PST

I need to add Wallet One payment system to my application. After reading this post stf Post I go to Wallet One github

I Copy lib/walletone folder to my project in lib/ And change my application.rb file:

require_relative 'boot'  require 'rails/all'  require_relative '../lib/walletone/walletonemiddleware.rb'  require '../lib/walletone/middleware'  require '../lib/walletone/middleware/callback'  Bundler.require(*Rails.groups)    module Rshop    class Application < Rails::Application     config.middleware.use WalletoneMiddleware    end  end   

Add walletonemiddleware.rb class to lib/walletone

class WalletoneMiddleware < Walletone::Middleware::Base    def perform notify, env      raise 'Wrong sign' unless notify.valid? W1_SECRET_KEY      # TODO something with notify      'Return some message for OK response'    end  end  

But when I start my server, got this error:

/home/zeus/RubymineProjects/rshop/lib/walletone/walletonemiddleware.rb:1:in `<top (required)>': uninitialized constant Walletone (NameError)      from /home/zeus/RubymineProjects/rshop/config/application.rb:3:in `require_relative'      from /home/zeus/RubymineProjects/rshop/config/application.rb:3:in `<top (required)>'      from /home/zeus/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/railties-5.0.0.1/lib/rails/commands/commands_tasks.rb:88:in `require'      from /home/zeus/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/railties-5.0.0.1/lib/rails/commands/commands_tasks.rb:88:in `block in server'      from /home/zeus/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/railties-5.0.0.1/lib/rails/commands/commands_tasks.rb:85:in `tap'      from /home/zeus/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/railties-5.0.0.1/lib/rails/commands/commands_tasks.rb:85:in `server'      from /home/zeus/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/railties-5.0.0.1/lib/rails/commands/commands_tasks.rb:49:in `run_command!'      from /home/zeus/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/railties-5.0.0.1/lib/rails/commands.rb:18:in `<top (required)>'      from /home/zeus/RubymineProjects/rshop/bin/rails:9:in `require'      from /home/zeus/RubymineProjects/rshop/bin/rails:9:in `<top (required)>'      from /home/zeus/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/spring-2.0.0/lib/spring/client/rails.rb:28:in `load'      from /home/zeus/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/spring-2.0.0/lib/spring/client/rails.rb:28:in `call'      from /home/zeus/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/spring-2.0.0/lib/spring/client/command.rb:7:in `call'      from /home/zeus/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/spring-2.0.0/lib/spring/client.rb:30:in `run'      from /home/zeus/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/spring-2.0.0/bin/spring:49:in `<top (required)>'      from /home/zeus/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/spring-2.0.0/lib/spring/binstub.rb:31:in `load'      from /home/zeus/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/spring-2.0.0/lib/spring/binstub.rb:31:in `<top (required)>'      from /home/zeus/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:68:in `require'      from /home/zeus/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:68:in `require'      from /home/zeus/RubymineProjects/rshop/bin/spring:14:in `<top (required)>'      from bin/rails:3:in `load'      from bin/rails:3:in `<main>'  

What I have to include to add Walletone namespace ?

belongs_to more than one associated record

Posted: 24 Dec 2016 12:21 AM PST

Sorry for this nooby question.

Reading this here : guides.rugyonrails

It says that the belongs_to association is appropriate when each book can be assigned to exactly one author. But what is the best practice if a book can have several authors?

I need a table Books and a table Authors, where Books can have 1 to 10 authors.

Thanks !

Simple referral system in rails

Posted: 24 Dec 2016 06:21 AM PST

I'm making a very simple referral system, but the issue I'm seeing is that I need to make two different calls to the DB with a single submit action and I'm not sure how to do that.

The general idea for the system is as follows:

  • A visitor subscribes to the mailing list and receives an email with a referral link with some kind of query string parameter identifying them (e.g. www.domain.com?referrer_id=1)
  • When another visitor uses this referral link and signs up, I store a) the new subscriber's email address, and b) the referral information

This would be stored in two tables:

  • subscribers table with | id | email | referrer |
  • referrals table with | id | subscriber_id | referrals |, where referrals is the number of times a subscriber has referred other subscribers

Again, I'm wondering how to make two calls -- one for the new subscriber and one for the referral information -- with a single submit action. Or, if that's not the best approach, how to do this using best practices.

Whats a good ruby IDE with rails? [on hold]

Posted: 23 Dec 2016 11:46 PM PST

I am looking to learn ruby on rails. Actually I have to learn it for my internship. So I was looking into some IDEs and so far I learned that cloud 9 is good but it asks me for my credit card info even for the free version. Any good free IDE for ruby and ruby on rails? Or should I just get cloud 9?

Thank you for your time.

Rails - how to delete duplicate cookies across subdomains?

Posted: 23 Dec 2016 10:44 PM PST

Since I wanted to start supporting cross subdomain logins on my website. So I changed my session store config from

MyApp::Application.config.session_store :cookie_store,    key: '_my_app_session'  

to

MyApp::Application.config.session_store :cookie_store,    key: '_my_app_session',    domain: '.local.host', # I'm using *.local.host for 127.0.0.1    tld_length: 2  

After that, uses got 2 cookies with same name as list below, which caused uses could be logged out. I was using Devise, and it only delete _my_app_session under .local.host. So the user was kept signed in.

Name                Value           Domain  _my_app_session     abc             www.local.host  _my_app_session     xyz             .local.host  

How can I delete both of the cookies?

How to pass default filter into Filterrific get

Posted: 23 Dec 2016 10:14 PM PST

I finally got my filterrific get working and its a great gem, if not a little complex for a noob like me.

My original index page was filtering the active records based on those nearby to the user like this:

def index     location_ids = Location.near([session[:latitude], session[:longitude]], 50, order: '').pluck(:id)  @vendor_locations = VendorLocation.includes(:location).where(location_id: location_ids)    @appointments = Appointment.includes(:vendor).    where(vendor_id: @vendor_locations.select(:vendor_id))    end  

So this pulls in all of the Appointments with Vendors in the area, but how do I pass this over to the Filterrific search:

@filterrific = initialize_filterrific(    params[:filterrific],    select_options:{ sorted_by: Appointment.options_for_sorted_by, with_service_id: Service.options_for_select },    ) or return    @appointments = @filterrific.find.page(params[:page])    respond_to do |format|    format.html    format.js  end  

It seems like the Filterrerrific is loading ALL of the appointments by default, but I want to limit to the ones nearby. What am I missing?

Parsing XML HTTParty response

Posted: 23 Dec 2016 10:06 PM PST

I was getting data from an api using HTTParty. I managed to get back the XML response, and it looks like HTTParty has made that xml response into Ruby.

How can I navigate through the hashes and get the data I need? For instance, say I wanted the "Name", which is "29TH AVENUE STN/ARBUTUS".

The API key works fine, since I am getting a response back.

Just not too sure how I can navigate through and get the data I want, and to put it into my view.

index.html.erb:

<% @courses.each do |course| %>  <%= course %>    <% end %>  

HTTparty response:

["Route", {  "RouteNo" => "016", "Name" => "29TH AVENUE STN/ARBUTUS ", "OperatingCompany" => "CMBC", "Patterns" => {      "Pattern" => [{          "PatternNo" => "E5TP", "Destination" => "29TH AVE STN", "RouteMap" => {              "Href" => "http://nb.translink.ca/geodata/trip/016-E5TP.kmz"          }, "Direction" => "EAST"      }, {          "PatternNo" => "EB1", "Destination" => "29TH AVE STN", "RouteMap" => {              "Href" => "http://nb.translink.ca/geodata/trip/016-EB1.kmz"          }, "Direction" => "EAST"      }, {          "PatternNo" => "EB5", "Destination" => "29TH AVE STN", "RouteMap" => {              "Href" => "http://nb.translink.ca/geodata/trip/016-EB5.kmz"          }, "Direction" => "EAST"      }]  }  }]  

Model for getting the response

class Checker    include HTTParty    base_uri 'http://api.translink.ca/rttiapi/v1/routes'  default_params apikey: "[my proper api key]"  format :xml    def self.for term    get("", query: {stopNo: term})["Routes"]["Route"]["RouteNo"]    end  end  

Controller for the Model

  class TimesController < ApplicationController    def index      @search_term = '51048'      @courses = Checker.for(@search_term)    end  end  

1 comment:

  1. Sometime it becomes very hard to find a well written and well established bog which give you correct and useful information. However, I found this blog and got some relevant information which are really helpful for me.rb88

    ReplyDelete