Wednesday, October 5, 2016

JSON API implmentation for service object in Rails | Fixed issues

JSON API implmentation for service object in Rails | Fixed issues


JSON API implmentation for service object in Rails

Posted: 05 Oct 2016 07:44 AM PDT

As you know, service object is used to create data for multiple domains, or connect 3rd party APIs in one procedure.

So in this case, resource interface and domain model are not exactly matched.

For example, you want to create Subscription. The procedure is following,

  1. create User
  2. create choose the Plan
  3. create Subscription (connecting third party API)

    • If something fails, the rollback occurs.

The business logic is across more than one domain. So I could do POST with those JSON data.

{"plan_id": 1,   "user_info":{"uuid": "644e1dd7-2a7f-18fb-b8ed-ed78c3f92c2b",                "name": "John Doe",                "email": "john@gmailcom"},   "user_card_info": {"object":"card",                      "exp_month": 12,                      "exp_year": 2020,                      "number": 4242424242424242}   }  

In this case, how should I handle this situation in JSON API. Maybe Should I create abstract resource? Also How can I handle this within Controller in JSON API?

Animation firing twice when visiting a cached page by Turbolinks 5

Posted: 05 Oct 2016 07:50 AM PDT

I'm using Animate.css and I have a div with the animated and fadeIn classes. The div fades in fine on initial visit, but when it's visited a second time (i.e. once the page is already cached by turbolinks), the fadeIn animation occurs twice -- once when the cache preview is shown (this happens instantly), and once after the page is actually loaded. How can I fix this and make the animation run only once?

application.js

//= require jquery  //= require bootstrap-sprockets  //= require jquery_ujs  //= require turbolinks  //= require_tree .  

Looking for Ruby on Rails Process Engine

Posted: 05 Oct 2016 07:27 AM PDT

I am looking for a Process Engine for Ruby on Rails or a another way to solve my problem.

When I am thinking of a Process Engine I mean something like Activiti for Java with Spring Boot.

I want something where I can:

  • Implement state-machine like processes (For example in BPMN2.0 process or as Class)
  • Instances of processes are always persisted.
  • I can add delays or waiting conditions to jumps from one state to the other or timeouts on waits etc...
  • (Optional) I can have a system to deploy new versions of my processes into a live system. (Old versions keep running until finished)

I need this to model users for example doing a WebApp assisted activity over the course of a day, where I need to enact escallations wherever necessary.

For example: Go do Job A and enter Code X. If code X hasn't arrived 2 hours later, do Escallation M, otherwise depending on code go do Job B or Job C. And all this can only till a certain time of the day it was started or do Escallation N.

Rails 5 Paranoia - How can I 'show' a deleted record?

Posted: 05 Oct 2016 07:45 AM PDT

Upon soft-deleting a record, I'm unable to call it on the show action on the controller, for it looks for a record matching the record's ID WHERE deleted_at IS NULLL, which is correct given the purpose of the gem, but I'd still like to be able to access it on a sort of a "readonly" state, within the application, in order to allow the user to review the archive and possibly restore it.

How can I work around the deletion scope so that I can access the object again?

New gateway for active merchant gem

Posted: 05 Oct 2016 06:46 AM PDT

I have a new gateway, and this is not in the active merchant option, for security reasons and time y can not include it, I want to use the active merchant gem and in my project folder have this new gateway, What can I do?

Today I have a complete active merchant in my rails proyect in a lib folder and puts my gateway inside the folder, I am make some others configurations and it works for me, but the process is very cumbersome to maintain and update this gem...

Ambiguous match, found 2 elements matching css - Capybara

Posted: 05 Oct 2016 07:11 AM PDT

I have a that renders two of the same elements on the page. I understand what the problem is with the error but I'm just not sure how to fix it? Here is my test:

TEST

 it "deletes the correct snitch" do          user    = login_user          snitch  = create(:snitch, :healthy, owner: user.accounts.first)          snitch2 = create(:snitch, :healthy, owner: user.accounts.first)            visit root_path          delete = page.find(".icon-delete")          first(delete).click          expect(page).to have_content("Please confirm this delete.")       end  

ERROR

 Managing snitches deleting a snitch from the index page deletes the correct snitch   Failure/Error: delete = page.find(".icon-delete")     Capybara::Ambiguous:     Ambiguous match, found 2 elements matching css ".icon-delete"  

How can I pick just one of the icon delete on the page?

Rails exception_handler gem

Posted: 05 Oct 2016 06:43 AM PDT

I've installed Rails excpetion_handler and tried following the instructions to setup custom error handling, however I'm still getting the standard 500 error message that the gem creates:

500 Internal Server Error If you are the administrator of this website, then please read this web application's log file and/or the web server's log file to find out what went wrong.

Here's what I added to config/application.rb:

class Application < Rails::Application    config.exception_handler = {        dev: true,        layouts: {          '500' => 'exception'        }    }  end  

I created an exception layout at layouts/exception.html.erb:

<!DOCTYPE html>  <html>    <head>      <title><%= "Error - #{@exception.status} Error" %></title>    </head>      <body>        <div class="container">        <%= yield %>      </div>      </body>  </html>  

And generated the default exception views with: rails generate exception_handler:views

<div class="error">      <% if /^(5[0-9]{2})$/ =~ @exception.status.to_s %>            <!--Message -->          <%= content_tag :div, class: "message" do %>              <%= content_tag :div, class: "title" do %>                  <span><%= "#{@exception.status} Error - #{details[:name]}" %></span>                  <%= link_to image_tag("exception_handler/close.png"), main_app.root_url, title: "Close (Go back home)", class: "close" %>              <% end %>                <%= content_tag :div, class: "details" do %>                  <%= image_tag "exception_handler/alert.png", title: "#{@exception.status} Error" %>                  <div class="status"><%= @exception.status %> Error</div>              <% end %>                <%= content_tag :div, class: "info" do %>                  <span><%= details[:description] %></span>                  <div class="notification">                      <%= link_to image_tag("exception_handler/home.png", title: "Go Back Home"), main_app.root_url, class: "home" %>                      <div class="version">v<%= Rails.version %></div>                      <strong>Our developers have been notified - we're working on it!</strong>                  </div>              <% end %>            <% end %>        <% else %>            <%= content_tag :div, details[:description], class: "message" %>        <% end %>  </div>  

I've tried restarting my rails server just to make sure the changes are taking effect, but it still doesn't work. What have I missed?

Why do all my radio buttons share a single selection?

Posted: 05 Oct 2016 07:34 AM PDT

I'm trying to build a survey app and I've hit a roadblock. When I'm submitting a response to a survey, all my answers share the same radio button selection id which means that I can only select one radio button across multiple questions whereas I want this to be one radio button per question.

I'm baffled and would very much appreciate some help.

I'm using simple_form for this project.

views/responses/_form.html.erb

<%= @response %>  <%= @response.survey_id %>    <%= @survey.name %>    <p>    <strong>Name:</strong>    <%= @survey.name %>  </p>    <p>    <strong>End date:</strong>    <%= @survey.end_date %>  </p>    <p>    <%= simple_form_for [@survey, @response] do |f| %>      <!-- Survey id -->      <%= f.hidden_field :survey_id, :value => @survey.id %>          <!-- Questions -->        <ol>          <% @survey.questions.each do |q| %>            <li><%= q.content %></li>              <!-- Iterate through answers for this question -->            <%= f.simple_fields_for :answers do |a| %>              <%= f.association :answers, collection: q.answers, as: :radio_buttons, :item_wrapper_class => 'test_class', include_blank: false %>            <% end %>            <% end %>        </ol>          <%= f.submit %>    <% end %>  </p>  

Models

survey.rb

class Survey < ApplicationRecord    has_many :questions, :dependent => :destroy    has_and_belongs_to_many :responses      validates_presence_of :name    accepts_nested_attributes_for :questions, allow_destroy: true  end   

question.rb

class Question < ApplicationRecord    belongs_to :survey, optional: true    has_many :answers, :dependent => :destroy    accepts_nested_attributes_for :answers, allow_destroy: true  end  

answer.rb

class Answer < ApplicationRecord    belongs_to :question, optional: true    belongs_to :response, optional: true      def to_label      "#{content}"    end  end  

response.rb

class Response < ApplicationRecord    belongs_to :survey, optional: true    belongs_to :user, optional: true      has_and_belongs_to_many :answers, :dependent => :destroy  end  

Thanks, Bhams

Edit:

Generated HTML

<p>    <form novalidate="novalidate" class="simple_form new_response" id="new_response" action="/surveys/9/responses" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="&#x2713;" /><input type="hidden" name="authenticity_token" value="39QorGeTDhu7pojy3L6gbZ1GZh9yBhqZphFMRWD++Ghd2ScWeLVEcdyhD9Ym0JyKHLptghvLOnJP9UlmHn32Bw==" />      <!-- Survey id -->      <input value="9" type="hidden" name="response[survey_id]" id="response_survey_id" />          <!-- Questions -->        <ol>            <li>222</li>              <!-- Iterate through answers for this question -->                <div class="input radio_buttons optional response_answers"><label class="radio_buttons optional">Answers</label><input type="hidden" name="response[answer_ids]" value="" /><span class="radio test_class"><label for="response_answer_ids_35"><input class="radio_buttons optional" type="radio" value="35" name="response[answer_ids]" id="response_answer_ids_35" />11111</label></span><span class="radio test_class"><label for="response_answer_ids_36"><input class="radio_buttons optional" type="radio" value="36" name="response[answer_ids]" id="response_answer_ids_36" />2222</label></span><span class="radio test_class"><label for="response_answer_ids_37"><input class="radio_buttons optional" type="radio" value="37" name="response[answer_ids]" id="response_answer_ids_37" />33333</label></span><span class="radio test_class"><label for="response_answer_ids_38"><input class="radio_buttons optional" type="radio" value="38" name="response[answer_ids]" id="response_answer_ids_38" />444444</label></span><span class="radio test_class"><label for="response_answer_ids_39"><input class="radio_buttons optional" type="radio" value="39" name="response[answer_ids]" id="response_answer_ids_39" />55555</label></span></div>              <li>33333333333</li>              <!-- Iterate through answers for this question -->                <div class="input radio_buttons optional response_answers"><label class="radio_buttons optional">Answers</label><input type="hidden" name="response[answer_ids]" value="" /><span class="radio test_class"><label for="response_answer_ids_40"><input class="radio_buttons optional" type="radio" value="40" name="response[answer_ids]" id="response_answer_ids_40" />4444444444444</label></span><span class="radio test_class"><label for="response_answer_ids_41"><input class="radio_buttons optional" type="radio" value="41" name="response[answer_ids]" id="response_answer_ids_41" />55555</label></span></div>          </ol>          <input type="submit" name="commit" value="Create Response" data-disable-with="Create Response" />  </form></p>  

Non specific MVC framework ruby gems and example code to Rails framework

Posted: 05 Oct 2016 06:43 AM PDT

I have been learning Ruby on Rails, but I still have issues when it comes to Ruby gems with examples that are irb based and not Rails or Sinatra framework based. I am trying to implement the Block.io Bitcoin API functionality. But the code I find is Ruby only, so I am not sure where to create a config file for the API Key and also whether I need to create a controller to make this work in the views for Rails.

The gem and examples are on: https://github.com/BlockIo/gem-block-io

I installed this gem via bundle install on Rails

gem install block_io -v=1.0.6  

The Ruby example show the following:

>> require 'block_io'  >> BlockIo.set_options :api_key=> 'API KEY', :pin => 'SECRET PIN', :version => 2  

In Rails which config file would I enter the above api_key and pin?

In the example they show the code to get your address as follows:

BlockIo.get_my_address  

Do I need to create a function in a controller such as:

def address   @my_address = BlockIo.get_my_addresses  end  

and in the view use:

<%= @my_address %>  

I need some guidance with regards to the above, any comment or assistance will be greatly appreciated.

Validate, prefill and potentially block while typing

Posted: 05 Oct 2016 05:56 AM PDT

I have a field where user has to fill in their social security number.

If the users birthdate is the 14th of November 1990

The social security starts with 90.11.14-XXX.XX (X represents random number 0-9)

I'm using simple_form

<%= f.input :ssn,               label: t('employee.social_security_no'),              input_html: { placeholder: "XX.XX.XX - XXX.XX" }%>  

I would like to achieve the following:

1) How can I preset the input field set with 90.11.27-_ _ _ . _ _

2) and validate that the remaining 5 numbers are actually numbers

3) and limit the field so that user cannot fill in more than 5 extra digits.

Any help to get me on the way is greatly appreciated.

Not able to use "number_with_precision" in ApplicationHelper's method in Rails 5.0

Posted: 05 Oct 2016 06:33 AM PDT

i am using "number_with_precision" method in Rails View, it is working fine there, for example:

In Rails View: (Works Fine)

<%= number_with_precision(job.company.rating, :precision => 2) %>  

But when i try to do the same in ApplicationHelper's method then it gives me the following error: undefined method `number_with_precision' rails

here is what i have tried:

In Rails ApplicationHelper: (Gives Error)

module ApplicationHelper      def employer_overall_rating(overall_rating)        @overall_rating = number_with_precision(overall_rating, :precision => 2)    end    end  

Please let me know how i can use the same in ApplicationHelper.

Thanks.

Javascript is not executed

Posted: 05 Oct 2016 05:44 AM PDT

i cant figure out, why my javascript is not executed (and its really not executed).

/app/assets/javascripts/application.js:

//= require jquery  //= require bootstrap-sprockets  //= require turbolinks  //= require jquery_ujs  //= require_tree .  

/app/controllers/project_controller.rb:

def upload      @projects = Project.all.order(updated_at: :desc)      @project = Project.find(params[:id])      respond_to do |format|          format.html          format.js {render layout: false}      end  end  

/app/views/projects/show.html.erb:

<%= link_to project_upload_path, :project => @project.id, class: "btn btn-default" do %>      Upload &nbsp;      <%= glyph("plus") %>  <% end %>  

/app/views/projects/upload.html.erb:

<div class="row">      <div class="col-xs-12">          <h2>Upload File to <%= @project.name %> project</h1>      </div>      <br>      <div class="col-xs-12">          <%= render :partial => "uploadform", :action => "savefile" %>      </div>  </div>  

/app/views/projects/_uploadform.html.erb:

<%= form_for :upload, url: {action: "savefile"}, :multipart => true  do |f| %>      <%= f.hidden_field(:project_id, :value => params[:id]) %>      <%= f.file_field :file, input_html: { hidden: true }, label: 'Upload Attachment'  %>      <input id="file-display" class="input-large uneditable-input" type="text">      <%= f.submit "Save File", :class => "btn btn-default btn-file", :id => "upload-btn" %>  <% end %>  

/app/views/projects/upload.js.erb:

$(document).on('ajax:success', function() {      alert("Test");  });  

I tried everything. I added and removed "{render layout: false}" in my controller. I tried "page:change" and "turbolinks:load" in my upload.js.erb (instead of "ajax:success"). I tried all of the Java-Ready functions in "_uploadform.js.erb" (instead of "upload.js.erb"). I tried "remote: true" in link_to (show.html.erb) - but then it only executes js.erb (just the alert came up). I also updated Rails from 4.2.1 to 4.2.7.1 and tried "//= require jquery.turbolinks" in application.js (with all the document ready functions above).

As you can see in my log, it seems that it doesnt respond with the Javascript:

Started GET "/projects/upload/20" for 127.0.0.1 at 2016-10-05 14:05:48 +0200  Processing by ProjectsController#upload as HTML    Parameters: {"id"=>"20"}    Project Load (0.0ms)  SELECT  "projects".* FROM "projects" WHERE "projects"."id" = ? LIMIT 1  [["id", 20]]    Rendered projects/_uploadform.html.erb (0.0ms)    Rendered projects/upload.html.erb within layouts/application (2.4ms)  Completed 200 OK in 327ms (Views: 324.8ms | ActiveRecord: 0.0ms)  

Please help me. I dont understand why this is not working in any way.

Get progress of AJAX call to get JSON in Rails

Posted: 05 Oct 2016 05:45 AM PDT

I have the following JS to retrieve some JSON data from a controller method in a Rails app:

$.ajax({      xhr: function() {          var xhr = $.ajaxSettings.xhr();          xhr.onprogress = function(e) {              if (e.lengthComputable) {                  console.log(e.loaded / e.total);              }          };          xhr.upload.onprogress = function(e) {              if (e.lengthComputable) {                  console.log(e.loaded / e.total);              }          };          return xhr;      },      cache: false,      url: '/get_data',      method: 'GET',      dataType: 'JSON',      success: function(data) {          console.log(data);      }  });  

And the method is as follows:

def get_data    @data = [{....}]    respond_to do |format|      format.html      format.json do        render json: @data      end    end  end  

The method can take up to 3-4 seconds to return due to the @data being either large or requiring complex calculations first, so I want to show a progress bar whilst the AJAX is taking place.

Note: I don't just want to show a loader that shows before and after the AJAX, but actually show the progress!

However I'm finding that lengthComputable is always false...

How can I get Rails to send back the correct progress?

Ruby on Rails - multiple database connections

Posted: 05 Oct 2016 07:13 AM PDT

I'm developing an application where it lets users to establish many number of database connections with a has-many relationship between user and connections. The connections are passive until the user manually connects each. The motive is to perform queries on them, parallely.

I don't find good tutorials related to this, can you help me with some tips on how to accomplish this ?

Couldn't find record without an ID, Rails 4 and ActiveAdmin

Posted: 05 Oct 2016 05:37 AM PDT

I am implementing ActiveAdmin to CRUD my app's content. So far so good. But I am receiving error: Couldn't find Girl without and ID when I am accessing action 'New' in my admin panel.

enter image description here

My ActiveAdmin controller:

controller do         def create            @advertisement = Girl.new(girl_params)           respond_to do |format|           @advertisement.bypass_humanizer = true             if @advertisement.save                     if params[:images]                   params[:images].each { |image|                      @advertisement.pictures.create(image: image)                    }               end                format.html  {redirect_to admin_girl_path(@advertisement)}              format.json  { render :json => @advertisement, :status => :created, :location => @advertisement }             else               format.html { render :action => "new"  }             format.json { render json: @advertisement.errors.full_messages, status: :unprocessable_entity }           end        end     end        def new       @advertisement = Girl.new     end      def edit      @advertisement = Girl.find(params[:id])    end        def update         @advertisement = Girl.find(params[:id])         flash[:notice] = 'Girl was successfully updated.' if @girl.update(girl_params)             redirect_to :back   end       def show       @advertisement = Girl.find(params[:id])     end      def destroy       @advertisement = Girl.find(params[:id])       @advertisement.destroy                redirect_to :back          end          def girl_params         # NOTE: Using `strong_parameters` gem         params.required(:girl).permit(:id,:humanizer_question_id, :_destroy, :confirmed_at,:bypass_humanizer,:humanizer_answer, :identifier, :token,:name, :work1,:subname,:paid, :work2, :check, :can_add_review,:work3, :work4,:smsidentifier,:smsidentifier_confirmation,:provaider, :expiration,:your_ip,:in_blacklist,:admin_confirmed,:country_id, :region_id,:user_id,:phone_number,:image,:terms_of_service,:region,:age,:height,:weight,:description,:description_ru,:email, hour_ids: [], pictures_attributes: [:image], service_ids: [])      end    end    

I have no clue to start with. I can't see problem.

What I tried:

Changed girl_params to permit_params :id,:humanizer_question_id,... then

def create            @advertisement = Girl.new(permited_params[:girl])    end  

But that didn't solve the issue.

Thanks in advance for any help.

image-path in "*.css.scss" isn't converted to an actual path

Posted: 05 Oct 2016 06:02 AM PDT

I have a css which I've converted to *.css.scss online. I include it into application.css. In my *.css.scss I have this:

background: url(image-path 'something.png') ;  

But it doesn't work because "image-path" isn't converted to the actual path but stays at it is, as a string.

http://localhost:3000/assets/image-path%20%22something.png%22  

The image exists if I enter the path manually.

This throws an exception -- invalid syntax:

background: url(<%= image-path 'something.png' %>) ;  

How to return custom error codes in a Rails API?

Posted: 05 Oct 2016 06:14 AM PDT

Given a RESTful API, implemented in Rails, I want to include in the responses not only the errors messages, generated by ActiveModel::Validations, but also custom error codes. First of all I would like to point out that I am not talking about HTTP Status codes. I am talking about having an error of any type (from general errors like record not found to small validation errors like username can't be blank) be mapped to a unique numeric code, that is custom application-specific error codes. Let me give an example - given a list of error codes, like:

1: record not found  ... some other errors  # Validation errors for User model between 1000 to 2000   1001: first name can't be blank   1002: first name must contain at least 3 characters   1003: last name can't be blank   1004: last name must contain at least 3 characters   ...some other errors  

If I have a form for a user and submit it with empty fields for first and last name, I want to have in the response body something like:

{error_codes: [1001, 1002, 1003, 1004]}  

or something similar (for example I could have an array of error objects, each with a code, message for developer, message for user etc.). Let me give an example with the Twilio API, taken from RESTful API Design: what about errors?:

enter image description here

Here, 20003 is some custom Twilio-specific code. The question is - how can this be implemented in Rails? I see several difficult aspects:

  • how do I get a list of all possible errors that can be encountered. It is hard to get such a list even only for the validation errors, let alone the other types of errors that can occur.
  • how should this list be organized - maybe in a YAML file?
  • how do I access the list - maybe something similar to the way translations are accessed via I18n.t?

I will really appreciate any advice on the topic. Thank you.

P.S. I think this is a similar question.

No SSL caused by mixed content in ruby app

Posted: 05 Oct 2016 04:55 AM PDT

I have an APP written in Ruby. The authentication is made through Facebook-Graph_API.

I am using an SSL certificate which is validated through Globe SSL.

The connection is encrypted and almost everything is working fine. BUT!

The connection is insecure caused by mixed content. The pictures which the app is loading are coming through http. But I need this from an https source.

I found here:

Graph API for Facebook developers

that I have to use something like this:

return_ssl_resource => true

But I don´t know at which Position I have to paste this!

Does anybody have an example or experience with this? I you need further Information please let me know.

Thx for your help!

How to include subdirectories to autoload for Grape API?

Posted: 05 Oct 2016 04:41 AM PDT

I'm using Grape to build an API for a Rails project (I'm mounting the grape project in rails routes.rb something like mount Backend::Base => '/').

The files structure is something like:

├── app │   ├── api │   │   └── backend │   │   ├── base.rb │   │   └── v1 │   │   ├── alerts.rb │   │   ├── test │   │   │   └── index.rb

My application.rb includes:

config.paths.add "app/api", glob: "**/*.rb"    config.paths.add File.join('app', 'api'), glob: File.join('**', '*.rb')  config.autoload_paths += Dir[Rails.root.join('app', 'api', '*')]  

For base.rb:

module Backend    class Base < Grape::API        format :json      prefix :api        mount CanopyBackend::V1::Alerts      mount CanopyBackend::V1::Test::Index      end  end  

My alerts.rb:

module Backend    module V1      class Alerts < Grape::API        include Backend::V1::Defaults          resource :alerts do          get do            "alerts"          end        end      end    end  end  

And test/index.rb:

module Backend    module V1      module Test        class Index < Grape::API          include Backend::V1::Defaults            resource :index do            get do              "index"            end          end        end        end    end  end  

Now it seems I can access GET api/v1/alerts but not api/v1/test/index somehow.

I tried to modify config.autoload_paths += Dir[Rails.root.join('app', 'api', '*')] in application.rb to make it config.autoload_paths += Dir[Rails.root.join('app', 'api', '/**/')] but without any luck.

Any help?

Stubbing with WebMock not intercepting request

Posted: 05 Oct 2016 04:40 AM PDT

I'm attempting to stub a request to a Controller using WebMock. However, as I'm creating the stub, the request isn't being intercepted the way I'd expect or want it to be.

The Controller does nothing but render JSON based on the query parameter:

def index          render json: MyThing.search(params[:query]).as_json(only: [:id], methods: [:name_with_path])  end  

And the stubbing goes as follows:

mything_val = { ...json values... }  stub_request(:any, mything_path).with(query: { "query" => "a+thing" }).to_return(body: mything_val, status: 200)  page.find('.MyThingInput > input').set('a thing')    # Note: I've tried this with and without the `query:` parameter, as well as   with and without specifying header info.  

This is triggering a React component. What it does is, when a word or words are entered into the input, it sends an AJAX request to mything_path with the inputted value, which returns as JSON several suggestions as to what the user might mean. These are in a li element within .MyThingInput-wrapper.

In the spec file, I include:

require 'support/feature_helper'  require 'support/feature_matchers'  require 'webmock/rspec'  WebMock.disable_net_connect!  

What's actually happening when I input the text into the React component however is that regardless of the WebMock stub, it's hitting the Controller, making the DB request, and failing due to some restrictions of the testing environment. My understanding of how this should work is that when the request is made to mything_url, it should be intercepted by WebMock which would return the values I pre-defined, and never hit the Controller at all.

My guess is that somehow I'm mocking the wrong URI, but honestly, at this point I'm really uncertain. Any and all input is appreciated, and I'm happy to clarify any points I've made here. Thanks massively!

cap staging deploy: bash: bundle: command not found

Posted: 05 Oct 2016 04:40 AM PDT

I am running my Rails 5 project on CentOS 7 with rbenv. When i run cap staging deploy i got the error:

cd /srv/www/stagings/testproject/current; bundle exec rake db:migrate RAILS_ENV=staging stderr: bash: bundle: command not found    ** DEPLOY FAILED  ** Refer to log/capistrano.log for details. Here are the last 20 lines:      INFO [f7a6296f] Finished in 0.256 seconds with exit status 0 (successful).  

I can run bundle install in deploy directory /srv/www/stagings/testproject/current without any problem.

.bash_profile

PATH=$PATH:$HOME/.local/bin:$HOME/bin  export PATH  export PATH="$HOME/.rbenv/bin:$PATH"  export PATH="$HOME/.rbenv/plugins/ruby-build/bin:$PATH"  eval "$(rbenv init -)"  

ruby, gem, bundler versions:

which ruby  ~/.rbenv/shims/ruby  which bundle  ~/.rbenv/shims/bundle'   which gem  ~/.rbenv/shims/gem  

I tried

 gem uninstall bundler   gem install bundler`  

doesn't work. Any help? Thank you very much!

Insert data into junction table

Posted: 05 Oct 2016 04:55 AM PDT

I am trying to insert a set of data into a junction. I want to be able to set the default set of products to every new merchant that is created, then the merchant will have options to set their prices availability etc based on their needs.

I have the current method define

def add_products    @product = Product.all    @product.each do |product|      @merchant = MerchantProducts.create!(product_id: product.id, merchant_id: self.id)    end  end  

problem I am getting is the below

uninitialized constant Merchant::MerchantProducts  

Error with instance variable in Index view

Posted: 05 Oct 2016 05:17 AM PDT

So in my tutors_controller.rb this is my index action

  def index      @tutor = Tutor.all      @tutor = @tutor.fees_search(params[:fees_search]) if params[:fees_search].present?    end  

and in my index.html.erb this is the view

<div class='container'>    <%= form_tag(tutors_path, method: :get) do %>      <%= label_tag 'fees_search', 'Max Fees' %>      <%= select_tag 'fees_search', options_for_select((10..50).step(10)) %>      <%= submit_tag 'Filter' %>    <% end %>    <% @tutor.each do |tutor| %>      <% unless tutor.admin? %>        <div class='row' id='tutor-listing'>          <div class='col-xs-4'>            <%= image_tag(tutor.profile.avatar.url, :class => "img-rounded" ) if tutor.profile.avatar? %>          </div>          <div class='col-xs-8'>            <h3><%= link_to tutor.full_name, tutor_path(tutor) %></h3>            <% unless tutor.subjects.nil? %>              <% tutor.subjects.each do |subs| %>                  <span class='badge'id='tutor-listing-badge'>                    <%= link_to subs.name, subject_path(subs) %>                  </span>              <% end %>            <% end %>            <% unless current_tutor %>              <%= button_to "Shortlist Tutor", add_to_cart_path(tutor.id), :method => :post %>            <% end %>          </div>        </div>       <% end %>    <% end %>  </div>  

So i understand that when the index view first renders, @tutor would simply be Tutor.all so it renders each individual tutor perfectly.

After trying to filter it though, i start receiving errors. The exact error is NoMethodError in Tutors#indexand the highlighted line is <% unless tutor.admin? %>

enter image description here

profile.rb model

class Profile < ActiveRecord::Base    belongs_to :tutor    scope :fees_to, -> (fees_to) { where("fees_to <= ?", "#{fees_to}") }  end  

tutor.rb model

class Tutor < ActiveRecord::Base    has_one :profile, dependent: :destroy    def self.fees_search(n)      @profile = Profile.fees_to(n)      if @profile.empty?        return Tutor.none      else        @profile.each do |y|          y.tutor        end      end    end  end  

I get that now my @tutor instance variable has obviously changed. But how do i go about resolving this problem? Should i be rendering a partial instead? Obviously my index action in my controller could be "better" also but i'm quite confused now as to what i should be doing.

Would appreciate any advice! Thank you!

How to test a method that filters on several conditions?

Posted: 05 Oct 2016 04:49 AM PDT

I'd like to improve specs for a convenience method that returns an array of users whose purchases are due tomorrow and will be paid using a certain payment method (ignoring other payment methods).

The specs are something along the lines of:

it "doesn't return users without purchases being due tomorrow" do    # create user and associated records that don't fit the time condition    expect(subject).to eq([])  end    context "with users who have purchases due tomorrow" do      it "returns users with $CERTAIN_PAYMENT_METHOD" do      # create different users with different payment methods,      # all matching the time condition.        expect(subject).to eq([user_1, user_2])    end        it "doesn't return users without $CERTAIN_PAYMENT_METHOD" do      # create user with credit card,      # matching the time condition.        expect(subject).to eq([])    end    end  

I see three possible approaches here:

  1. Approach used above: Set up arbitrary combinations of records, and expect things specific to a single condition, always asserting the whole array. The setup can be long and repetitive.
  2. Set up arbitrary combinations, and expect things to be included/excluded in the returned array. These "soft expectations" are great to read but can be very error-prone.
  3. Set up (nearly) all combinations of records, and have a single expectation. This creates no overlap but also leaves developers in the dark as to why this method returns this specific array.

All approaches have their drawbacks, and I'm wondering if there's a best practice how to test methods like these?

cucumber does not recognize my steps

Posted: 05 Oct 2016 04:08 AM PDT

Feature: Home page  As a HR manager of a company I am visiting the digipresent app for the first time  I want to be welcomed with a greeting         Scenario: User sees the welcome message          When: he goes to home page          Then: he should see the welcome message  

This file is named as features/home_page.feature

When (/^he goes to the home page$/) do       visit root_path  end    Then (/^he should see the welcome message$/)do       expect(page).to have_content("Welcome to Present")  end  

This file is present as features/step_definitions/home_page_steps.rb

$cucumber --require features features/home_page.feature when I do this, the steps are not getting recognised.

Feature: Home page  As a HR manager of a company I am visiting the digipresent app for the first time  I want to be welcomed with a greeting       Scenario: User sees the welcome message # features/home_page.feature:5          When: he goes to home page          Then: he should see the welcome message    1 scenario (1 passed)  0 steps  0m0.023s  

How to call multiple bash command and ssh in Ruby?

Posted: 05 Oct 2016 04:01 AM PDT

I want to do the following commands in ruby.

  1. ssh into another computer using ssh example@example
  2. set source file source ~/.profile
  3. cd to/some/folder
  4. call my shell script with parameters, a json formatted string ,./my_script.sh my_hash.to_json

However I am facing these problems: I call them in one line using backticks, it works, but it is a very bad practice in my opinion because it is not readable nor it is maintainable.

On the other hand, when I call my_hash.to_json, the resulted string has non-escaped double quotes, How do I escape them?

how to use ur friendly / slug properly in rails routes?

Posted: 05 Oct 2016 03:23 AM PDT

i have a table which i generated with scaffold, something like this

rails generate scaffold Book title:string year:integer etc...

only admin can access above table with url something like :

admin/books/book-1
admin/books/book-2

i use friendlyid gem to generate slug value, and i don't have problem with that.

but now i need to access a page in public and query book data based on slug string, i really have no idea how to make route accept an url like this :

public/book-1  

currently i do it with query string : public?book_id=123 and get the parameters like this : Book.where(:id=>params[book_id]) and i need to change it with slug way?

i tried to add this to my route file, but still no luck

# get 'public/:slug', to: 'public#detailed_book', as: 'slugged_post'  

please advice, kindly show me how to setup my route file correctly and how to get the parameter in controller.

Rubymine - code folding ALL rspec examples

Posted: 05 Oct 2016 03:03 AM PDT

Does anyone know if it's possible to code fold all rspec examples either automatically on opening a spec file or preferably by key binding from within Rubymine.

For a spec with lots of examples it would be very handy to just collapse all examples to get an overview of the complete spec for a model, controller, etc. This would make it far easier to review and check for any missing edge conditions for example.

What I would like is for the it block to code fold so that they result in something like...

it 'should blah blah blah' do ... end

... without having to manually code fold every individual example.

no implicit conversion of Pathname into String in login with google+ api

Posted: 05 Oct 2016 03:13 AM PDT

I am trying to implement login with Google+ Api with Omniauth.

sample code- omniauth.rb

Rails.application.config.middleware.use OmniAuth::Builder do  provider :google_oauth2, Rails.application.secrets.google_client_id,        Rails.application.secrets.google_client_secret  end  

secrets.yml

 development:     secret_key_base:81953bc9411692c38d1224b39cf5bc0084290fef92     google_client_id: f30mofk10me.apps.googleusercontent.com      google_client_secret: *********************      test:       secret_key_base:   afa40d5824fee961dcd1a598axxxxxxxxxxxxxxxxx    production:      secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>     google_client_id: <%= ENV["GOOGLE_CLIENT_ID"] %>     google_client_secret: <%= ENV["GOOGLE_CLIENT_SECRET"] %>  

Session controller.rb

 class SessionsController < ApplicationController        def create      auth = request.env["omniauth.auth"]      puts auth      session[:omniauth] = auth.except('extra')      user = User.sign_in_from_omniouth(auth)      session[:user_id] = user_id      redirect_to root_url, notice:"Sign In"  end  def destroy      session[:user_id] = nil      session[:omniauth] = nil      redirect_to root_url, notice:"Sign OUT"  end      end  

user.rb

   class User < ActiveRecord::Base     def self.sign_in_from_omniouth(auth)     find_by(provider: auth['provider'], uid: auth['uid'])||      create_user_from_omniauth(auth)    end     def self.create_user_from_omniauth(auth)    create(      provider:auth['provider'],      uid:auth['uid'],      name:auth['info']['name']  )    end  

end

Home controller.rb

class HomeController < ApplicationController    before_action :set_auth     def index    end     def profile    end    private    def set_auth  @auth = session[:omniauth] if session[:omniauth]  end  end  

Application controller.rb

class ApplicationController < ActionController::Base    protect_from_forgery with: :exception     private    def current_user  @current_user ||= User.find(session[:usr_id]) if session[:user_id]  end   helper_method :current_user   end  

Application.html.rb

 <ul class="nav navbar-nav navbar-right">   <% if current_user %>      <li>Signed in as:<%= current_user.name %> - <%= image_tag(@auth['info'] ['image'],width: '50',height:'50',class: 'img-circle') %></li>      <li><%= link_to "Sign Out", 'sign_out', method: :delete %></li>    <%else%>      <li>    <%= link_to(image_tag("Fecebook_logo.png", width:40,hight:40), "auth/facebook") %></li>      <li>    <%= link_to(image_tag("googleplus2.png", width:40,hight:40), "auth/google_oauth2") %></li>      <li>  <%= link_to(image_tag("twitter.png", width:40,hight:40), "auth/twitter") %></li>     <%end%>   </ul>  

after all this set up i want to log in with google.It call to the redirected url http://localhost:9292/auth/google_oauth2/callback enter image description here

after allow that above error msg return...what should i do? thanks in advance

Using aggregate with options allowDiskUse in Mongoid

Posted: 05 Oct 2016 02:52 AM PDT

Problem:

My memory is getting exceeded while using sort in MongoDB query and tells me to use allowDiskUse:true option in the query. But in rails mongoid, aggregate function is not passing any options.

The error I am getting:

Sort exceeded memory limit of 104857600 bytes, but did not opt in to external sorting. Aborting operation. Pass allowDiskUse:true to opt in. (16819)  

My Code/Query:

result = ModelName.collection.aggregate([        {"$sort" => {            "created_at" => 1        }}      ], {'allowDiskUse' => true})  

My Objective:

To use allowDiskUse option in the mongoid query so that I can get the sorted data by created time but mongoid does not support it I guess, so I need some alternative. Any suggestions on what I should do ?

No comments:

Post a Comment