mardi 30 octobre 2018

SSL_connect returned=1 errno=0 state=unknown state: unknown protocol

After reading through many posts I couldn't find a solution to my problem. I've made a test connection with www.smtper.net which was successful. My error.log only tells me the error:

OpenSSL::SSL::SSLError: SSL_connect returned=1 errno=0 state=unknown state: unknown protocol

Maybe it has something to do with my nginx settings?

Issue

I'm trying to configure my smtp via mailgun (or gmail) but without success. My configuration in developement.rb looks like:

config.action_mailer.default_url_options = { :host => "xxxxx:8765" } 
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true
config.action_mailer.smtp_settings = {
   :address => "smtp.gmail.com",
   :port => 587,
   :domain => "mail.google.com",
   :user_name => "xxx@gmail.com",
   :password => "xxxxxx",
   :authentication => :plain,
   :enable_starttls_auto => true
}

I have installed OpenSSL 1.0.1f on my development server

How to style posts in bootstrap grid column

I have this code for posts that I want to show in bootstrap card column format.

%h4{:align => "center"} All Posts
%hr.my-3
- @posts.each do |post|
  %h4= link_to post.title, post
  %p= post.description
  %p= post.company

I want to show the first post in one card and the next in the other consistently across the whole page. Seems with the bootstrap code I need to manually input the individual posts. I would want it to be automated. Thanks

lundi 29 octobre 2018

How to upload a file using the file_file_tag?

I want to upload file in form but do not want its field inside a model. so using the file_filed_tag

at view:
 <%= form_tag services_datainterchange_path, method: :post, remote: true do %>
    <div class="row">
      <div class="col-sm-3 col-md-3">
        <div class="form-group">
          <%= label_tag :file %>
          <%= file_field_tag :file, required: true, class: "form-control", id: "upload_file" %>
        </div>
      </div>
      <div class="col-sm-2 col-md-2">
        <div class="form-group">
          <%= label_tag :name %>
          <%= text_field_tag :name, nil, required: true, class: "form-control", id: "upload_file_name" %>
        </div>
      </div>
      <div class="col-sm-2 col-md-2">
        <div class="form-group">
          <%= label_tag :source_type %>
          <%= select_tag :source_type, options_for_select(ApplicationRecord::SOURCE_TYPE), class: "form-control" %>
        </div>
      </div>
      <div class="col-sm-2 col-md-2">
        <div class="form-group">
          <%= label_tag :final_type %>
          <%= select_tag :final_type, options_for_select(ApplicationRecord::FINAL_TYPE), class: "form-control" %>
        </div>
      </div>
      <div class="col-sm-2 col-md-2">
        <div class="form-group">
          <%= submit_tag "Submit", class: "btn btn-primary" %>
        </div>
      </div>
    </div>
  <% end %>

At controller:

  directory = "public/job_files"
  Find.find( directory ) do |fpath|
    if FileTest.file?( fpath )
      fpath.clone(params[:file])
    end
  end

But file not upload the parameter do get submit of form. Thanks

Net::SMTPAuthenticationError for sending mail through rails action mailer

I am using rails action mailer but got this error "Net::SMTPAuthenticationError".I also enable the Less Secure apps but still got this error.

config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
    ActionMailer::Base.smtp_settings = {
    :user_name => "my_email",
    :password => "password",
    :domain => 'gmail.com',
    :address => 'smtp.gmail.com',
    :port => 587,
    :authentication => :plain 
    }

dimanche 28 octobre 2018

Ruby on rails Heroku deployment issue

I am completely new to ruby on rails and heroku. I deployed my first ruby on rails app to heroku and when I go to the website it says Application error.

Heroku Logs:

2018-10-28T13:56:03.196702+00:00 app[web.1]: from bin/rails:3:in <main>' 2018-10-28T13:56:03.316122+00:00 heroku[web.1]: State changed from starting to crashed 2018-10-28T13:56:03.287811+00:00 heroku[web.1]: Process exited with status 1 2018-10-28T19:40:08.313169+00:00 heroku[web.1]: State changed from crashed to starting 2018-10-28T19:40:14.732013+00:00 heroku[web.1]: Starting process with commandbin/rails server -p 38005 -e production2018-10-28T19:40:18.812465+00:00 heroku[web.1]: Process exited with status 1 2018-10-28T19:40:18.830606+00:00 heroku[web.1]: State changed from starting to crashed 2018-10-28T19:40:18.382604+00:00 app[web.1]: Ignoring bootsnap-1.3.2 because its extensions are not built. Try: gem pristine bootsnap --version 1.3.2 2018-10-28T19:40:18.722005+00:00 app[web.1]: /app/vendor/bundle/ruby/2.5.0/gems/bundler-1.15.2/lib/bundler/spec_set.rb:87:inblock in materialize': Could not find nokogiri-1.8.5 in any of the sources (Bundler::GemNotFound) 2018-10-28T19:40:18.722046+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.5.0/gems/bundler-1.15.2/lib/bundler/spec_set.rb:81:in map!' 2018-10-28T19:40:18.722048+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.5.0/gems/bundler-1.15.2/lib/bundler/spec_set.rb:81:inmaterialize' 2018-10-28T19:40:18.722050+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.5.0/gems/bundler-1.15.2/lib/bundler/definition.rb:159:in specs' 2018-10-28T19:40:18.722052+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.5.0/gems/bundler-1.15.2/lib/bundler/definition.rb:218:inspecs_for' 2018-10-28T19:40:18.722053+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.5.0/gems/bundler-1.15.2/lib/bundler/definition.rb:207:in requested_specs' 2018-10-28T19:40:18.722055+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.5.0/gems/bundler-1.15.2/lib/bundler/runtime.rb:109:inblock in definition_method' 2018-10-28T19:40:18.722057+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.5.0/gems/bundler-1.15.2/lib/bundler/runtime.rb:21:in setup' 2018-10-28T19:40:18.722058+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.5.0/gems/bundler-1.15.2/lib/bundler.rb:101:insetup' 2018-10-28T19:40:18.722060+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.5.0/gems/bundler-1.15.2/lib/bundler/setup.rb:19:in <top (required)>' 2018-10-28T19:40:18.722062+00:00 app[web.1]: from /usr/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:135:inrequire' 2018-10-28T19:40:18.722063+00:00 app[web.1]: from /usr/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:135:in rescue in require' 2018-10-28T19:40:18.722065+00:00 app[web.1]: from /usr/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:39:inrequire' 2018-10-28T19:40:18.722067+00:00 app[web.1]: from /app/config/boot.rb:3:in <top (required)>' 2018-10-28T19:40:18.722069+00:00 app[web.1]: from bin/rails:3:inrequire_relative' 2018-10-28T19:40:18.722071+00:00 app[web.1]: from bin/rails:3:in <main>' 2018-10-29T00:17:06.000000+00:00 app[api]: Build started by user ronald.fulton@gmail.com 2018-10-29T00:17:10.000000+00:00 app[api]: Build failed -- check your build logs 2018-10-29T00:17:58.000000+00:00 app[api]: Build started by user ronald.fulton@gmail.com 2018-10-29T00:18:21.892970+00:00 heroku[web.1]: State changed from crashed to starting 2018-10-29T00:18:21.304032+00:00 app[api]: Deploy 58877da3 by user ronald.fulton@gmail.com 2018-10-29T00:18:21.304032+00:00 app[api]: Release v13 created by user ronald.fulton@gmail.com 2018-10-29T00:18:24.000000+00:00 app[api]: Build succeeded 2018-10-29T00:18:27.506319+00:00 heroku[web.1]: Starting process with commandbin/rails server -p 27973 -e production2018-10-29T00:18:31.363624+00:00 app[web.1]: Ignoring bootsnap-1.3.2 because its extensions are not built. Try: gem pristine bootsnap --version 1.3.2 2018-10-29T00:18:31.824489+00:00 app[web.1]: /app/vendor/bundle/ruby/2.5.0/gems/bundler-1.15.2/lib/bundler/spec_set.rb:87:inblock in materialize': Could not find nokogiri-1.8.5 in any of the sources (Bundler::GemNotFound) 2018-10-29T00:18:31.824532+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.5.0/gems/bundler-1.15.2/lib/bundler/spec_set.rb:81:in map!' 2018-10-29T00:18:31.824536+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.5.0/gems/bundler-1.15.2/lib/bundler/spec_set.rb:81:inmaterialize' 2018-10-29T00:18:31.824537+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.5.0/gems/bundler-1.15.2/lib/bundler/definition.rb:159:in specs' 2018-10-29T00:18:31.824539+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.5.0/gems/bundler-1.15.2/lib/bundler/definition.rb:218:inspecs_for' 2018-10-29T00:18:31.824540+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.5.0/gems/bundler-1.15.2/lib/bundler/definition.rb:207:in requested_specs' 2018-10-29T00:18:31.824638+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.5.0/gems/bundler-1.15.2/lib/bundler/runtime.rb:109:inblock in definition_method' 2018-10-29T00:18:31.824640+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.5.0/gems/bundler-1.15.2/lib/bundler/runtime.rb:21:in setup' 2018-10-29T00:18:31.824641+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.5.0/gems/bundler-1.15.2/lib/bundler.rb:101:insetup' 2018-10-29T00:18:31.824643+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.5.0/gems/bundler-1.15.2/lib/bundler/setup.rb:19:in <top (required)>' 2018-10-29T00:18:31.824645+00:00 app[web.1]: from /usr/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:135:inrequire' 2018-10-29T00:18:31.824647+00:00 app[web.1]: from /usr/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:135:in rescue in require' 2018-10-29T00:18:31.824649+00:00 app[web.1]: from /usr/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:39:inrequire' 2018-10-29T00:18:31.824650+00:00 app[web.1]: from /app/config/boot.rb:3:in <top (required)>' 2018-10-29T00:18:31.824652+00:00 app[web.1]: from bin/rails:3:inrequire_relative' 2018-10-29T00:18:31.824654+00:00 app[web.1]: from bin/rails:3:in <main>' 2018-10-29T00:18:31.941992+00:00 heroku[web.1]: Process exited with status 1 2018-10-29T00:18:31.958003+00:00 heroku[web.1]: State changed from starting to crashed 2018-10-29T00:18:31.959507+00:00 heroku[web.1]: State changed from crashed to starting 2018-10-29T00:18:37.269542+00:00 heroku[web.1]: Starting process with commandbin/rails server -p 41633 -e production2018-10-29T00:18:41.490161+00:00 heroku[web.1]: State changed from starting to crashed 2018-10-29T00:18:41.084007+00:00 app[web.1]: Ignoring bootsnap-1.3.2 because its extensions are not built. Try: gem pristine bootsnap --version 1.3.2 2018-10-29T00:18:41.397420+00:00 app[web.1]: /app/vendor/bundle/ruby/2.5.0/gems/bundler-1.15.2/lib/bundler/spec_set.rb:87:inblock in materialize': Could not find nokogiri-1.8.5 in any of the sources (Bundler::GemNotFound) 2018-10-29T00:18:41.397450+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.5.0/gems/bundler-1.15.2/lib/bundler/spec_set.rb:81:in map!' 2018-10-29T00:18:41.397458+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.5.0/gems/bundler-1.15.2/lib/bundler/spec_set.rb:81:inmaterialize' 2018-10-29T00:18:41.397460+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.5.0/gems/bundler-1.15.2/lib/bundler/definition.rb:159:in specs' 2018-10-29T00:18:41.397462+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.5.0/gems/bundler-1.15.2/lib/bundler/definition.rb:218:inspecs_for' 2018-10-29T00:18:41.397463+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.5.0/gems/bundler-1.15.2/lib/bundler/definition.rb:207:in requested_specs' 2018-10-29T00:18:41.397469+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.5.0/gems/bundler-1.15.2/lib/bundler/runtime.rb:109:inblock in definition_method' 2018-10-29T00:18:41.397471+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.5.0/gems/bundler-1.15.2/lib/bundler/runtime.rb:21:in setup' 2018-10-29T00:18:41.397473+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.5.0/gems/bundler-1.15.2/lib/bundler.rb:101:insetup' 2018-10-29T00:18:41.397475+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.5.0/gems/bundler-1.15.2/lib/bundler/setup.rb:19:in <top (required)>' 2018-10-29T00:18:41.397481+00:00 app[web.1]: from /usr/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:135:inrequire' 2018-10-29T00:18:41.397483+00:00 app[web.1]: from /usr/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:135:in rescue in require' 2018-10-29T00:18:41.397485+00:00 app[web.1]: from /usr/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:39:inrequire' 2018-10-29T00:18:41.397491+00:00 app[web.1]: from /app/config/boot.rb:3:in <top (required)>' 2018-10-29T00:18:41.397502+00:00 app[web.1]: from bin/rails:3:inrequire_relative' 2018-10-29T00:18:41.397512+00:00 app[web.1]: from bin/rails:3:in <main>' 2018-10-29T00:18:41.466149+00:00 heroku[web.1]: Process exited with status 1 2018-10-29T00:18:41.735532+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/robots.txt" host=morning-hamlet-16155.herokuapp.com request_id=e4e2ab8d-d442-45ee-a299-1f4d9d60d290 fwd="96.234.235.202" dyno= connect= service= status=503 bytes= protocol=https 2018-10-29T00:18:42.520766+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=morning-hamlet-16155.herokuapp.com request_id=32cfec4c-0f51-4254-9d59-09828813c74f fwd="96.234.235.202" dyno= connect= service= status=503 bytes= protocol=https 2018-10-29T00:18:42.894502+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/robots.txt" host=morning-hamlet-16155.herokuapp.com request_id=253496a8-f522-447c-b1e5-01b12dc72d15 fwd="96.234.235.202" dyno= connect= service= status=503 bytes= protocol=https 2018-10-29T00:18:43.130329+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=morning-hamlet-16155.herokuapp.com request_id=ef099caf-0669-429a-9a6c-5703c93a542d fwd="96.234.235.202" dyno= connect= service= status=503 bytes= protocol=https 2018-10-29T00:18:43.507737+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/robots.txt" host=morning-hamlet-16155.herokuapp.com request_id=6855b0ec-5723-4ada-bd1f-5df8e8c1ac49 fwd="96.234.235.202" dyno= connect= service= status=503 bytes= protocol=https 2018-10-29T00:18:44.457736+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=morning-hamlet-16155.herokuapp.com request_id=17f4a6fb-76ff-4bb2-bf29-ed6b702c477d fwd="96.234.235.202" dyno= connect= service= status=503 bytes= protocol=https 2018-10-29T00:40:38.462970+00:00 heroku[web.1]: State changed from crashed to starting 2018-10-29T00:40:43.768770+00:00 heroku[web.1]: Starting process with commandbin/rails server -p 43245 -e production2018-10-29T00:40:47.367294+00:00 app[web.1]: Ignoring bootsnap-1.3.2 because its extensions are not built. Try: gem pristine bootsnap --version 1.3.2 2018-10-29T00:40:47.927710+00:00 app[web.1]: /app/vendor/bundle/ruby/2.5.0/gems/bundler-1.15.2/lib/bundler/spec_set.rb:87:inblock in materialize': Could not find nokogiri-1.8.5 in any of the sources (Bundler::GemNotFound) 2018-10-29T00:40:47.927736+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.5.0/gems/bundler-1.15.2/lib/bundler/spec_set.rb:81:in map!' 2018-10-29T00:40:47.927740+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.5.0/gems/bundler-1.15.2/lib/bundler/spec_set.rb:81:inmaterialize' 2018-10-29T00:40:47.927742+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.5.0/gems/bundler-1.15.2/lib/bundler/definition.rb:159:in specs' 2018-10-29T00:40:47.927744+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.5.0/gems/bundler-1.15.2/lib/bundler/definition.rb:218:inspecs_for' 2018-10-29T00:40:47.927745+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.5.0/gems/bundler-1.15.2/lib/bundler/definition.rb:207:in requested_specs' 2018-10-29T00:40:47.927748+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.5.0/gems/bundler-1.15.2/lib/bundler/runtime.rb:109:inblock in definition_method' 2018-10-29T00:40:47.927750+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.5.0/gems/bundler-1.15.2/lib/bundler/runtime.rb:21:in setup' 2018-10-29T00:40:47.927752+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.5.0/gems/bundler-1.15.2/lib/bundler.rb:101:insetup' 2018-10-29T00:40:47.927753+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.5.0/gems/bundler-1.15.2/lib/bundler/setup.rb:19:in <top (required)>' 2018-10-29T00:40:47.927756+00:00 app[web.1]: from /usr/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:135:inrequire' 2018-10-29T00:40:47.927758+00:00 app[web.1]: from /usr/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:135:in rescue in require' 2018-10-29T00:40:47.927759+00:00 app[web.1]: from /usr/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:39:inrequire' 2018-10-29T00:40:47.927762+00:00 app[web.1]: from /app/config/boot.rb:3:in <top (required)>' 2018-10-29T00:40:47.927764+00:00 app[web.1]: from bin/rails:3:inrequire_relative' 2018-10-29T00:40:47.927767+00:00 app[web.1]: from bin/rails:3:in `' 2018-10-29T00:40:48.028594+00:00 heroku[web.1]: State changed from starting to crashed 2018-10-29T00:40:48.011732+00:00 heroku[web.1]: Process exited with status 1 2018-10-29T01:42:48.359454+00:00 heroku[web.1]: State changed from crashed to starting

Thread.current keeps changing.

I'm running a rails instance using rails s in my local development branch. I'm trying to store a variable in my current thread .

 Thread.current[:group_id] = 2 

When i go to a different route in my same app, the key group_id is not present. When i checked with a debugger, the Thread.current was different than the previous one.

 1. #<Thread:0x007fa4dcbd17c0 run> 

 2. #<Thread:0x007fa4dbd1efe8 run> 

Can someone help me with this?

530-5.5.1 Authentication Required. Learn more at on rails app

am new to mails in rails.I am referring http://guides.rubyonrails.org/action_mailer_basics.html to learn. I am getting error like:

config.action_mailer.default_url_options = { :host => 'localhost:3000' }
ActionMailer::Base.smtp_settings = {

                :address        => "smtp.gmail.com",
                :port           => 587,
                :authentication => :plain,
                :user_name      => "<my gmail>@gmail.com",
                :password       => "<my gmail password>",
                :openssl_verify_mode  => 'none' }

I am try all answer but not resolved this problem.

vendredi 26 octobre 2018

open migration file from script

I'm writing a script to alter a bunch of tables at once in an app. But I'm stuck trying to write to the migration file that I'm generating,

here's what I have in the tool:

system "rails g migration AddDefaultValueToBooleans"
file = "#{Rails.root}db/migrate/*add_default_value_to_booleans.rb"

def replace(filepath, regexp, *args, &block)
  content = File.read(filepath).gsub(regexp, *args, &block)
  File.open(filepath, 'wb') { |file| file.write(content) }
end

replace( file, /^def change/mi) { |match| "change_column :my_table, :my_column, null: false, default: false" } 

replace is a nifty little method i found here https://stackoverflow.com/a/2141540/8480602

but it's not finding my file. i keep getting the error
No such file or directory @ rb_sysopen - root_path/migrate/*add_default_value_to_booleans.rb (Errno::ENOENT)

the filepath i'm using is wrong, but I can't seem to figure out how to write it correctly

How to exclude unwanted params from json object in rails 3.2

This is my url for ajax

def get_dataset

@reportdata = ReportAccountClose.where('ClosingType is not null')
@reporthp = @reportdata.map{|l| l.hp_entry}
x = {   data:@reportdata + @reporthp }         
render json: x
end

And My view for rendering datatable is

<script type="text/javascript">
  $('#ajax-table').DataTable({
 ajax: '/get_dataset',
   columns: [
{title: 'A/C NO', data: 'HPEntryId'},
{title: 'Name', data: 'Name'},
{title: 'VEHICLE NO', data: 'VehicleNumber'},
{title: 'TYPE', data: 'ClosingType'},
  ]
});
</script>

I want to filter HPEntryId which is present in @reportdata,@reporthp objects.How can i obtain filtered json response?

mercredi 24 octobre 2018

Redirection Issue while using https + Rails 3.0.10

Look for any help much appreciated..

I am using this Rails 3.0.10 application hosted on Heroku, which recently added ssl. And my Api::BaseController < ApplicationController looks something like this.

alias_method :original_inherited, :inherited

def inherited(subclass)
  original_inherited(subclass)

  load File.join("#{Rails.root}", "app", "controllers",
                 "api", "#{extract_filename(subclass)}")

  subclass.action_methods.each do |method|
    regex = Regexp.new("^(.*)_(\\d+)$")
    if match = regex.match(method)
      key = "#{subclass.to_s}##{match[1]}"
      @@versions[match[2].to_i] = true
      @@registered_methods[key] ||= {}
      @@registered_methods[key][match[2].to_i] = true

      subclass.instance_eval do
        define_method(match[1].to_sym) {}
      end
    end
  end
  subclass.reset_action_methods
end

def extract_filename(subclass)
  classname = subclass.to_s.split('::')[1]
  parts = classname.underscore.split('_')
  "#{parts.reject{|c| c == 'controller'}.join('_')}_controller.rb"
end

def reset_action_methods
  @action_methods = nil
  action_methods
end

When I make any request it comes here and in some APIs it makes redirection calls like this.

Status : 302 Found
Location : http://3a235934.ngrok.io/en/api/v2/vouchers/show_voucher?auth_token=SxSkyf4GykApgzhSyvWI&id=693

then gives response

Status Code: 200 OK
Cache-Control: max-age=0, private, must-revalidate
Content-Length: 82
Content-Type: application/json; charset=utf-8
Date: Thu, 25 Oct 2018 06:32:44 GMT
Etag: "92234fded00f59326ca858b732179de3"
Server: WEBrick/1.3.1 (Ruby/2.2.10/2018-03-28)
X-Runtime: 5.448165
X-Ua-Compatible: IE=Edge,chrome=1

has_many realtion in ruby on rails

I need to update a rails model,

has_many :unblocked_items, class_name: 'IncidentItem', 
           conditions: ['incident_items.item_type_id in (?) AND (incident_blocking_file_id IS NULL OR incident_blocking_files.way = ?)', IncidentItemType.blockable, BlockingWay.unblock],
           include: :incident_blocking_file
  has_many :blocked_items, class_name: 'IncidentItem',
           conditions: ['incident_items.item_type_id in (?) AND (incident_blocking_file_id IS NOT NULL AND (incident_blocking_files.way <> ? OR incident_blocking_files.way IS NULL))', IncidentItemType.blockable, BlockingWay.unblock],
           include: :incident_blocking_file

Get the following error Unknown key: :conditions. Valid keys are: :class_name, :anonymous_class, :foreign_key, :validate, :autosave, :table_name, :before_add, :after_add, :before_remove, :after_remove, :extend, :primary_key, :dependent, :as, :through, :source, :source_type, :inverse_of, :counter_cache, :join_table, :foreign_type (ArgumentError)

There is an easy way for making this change

mardi 23 octobre 2018

Rails lazy_high_charts: how to print a formatted time

I would to print into my charts the hours and minutes, for example "development: 27 h 30 m".

Now I have this:

enter image description here

In my script "data" represents "minutes"

{
  name: value.blank? ? "other" : value,
  data: all_weeks.merge(data_weeks.to_h).values.map do |data_value|
    data_value.nil? ? 0 : ( data_value.to_f / 60 ).round(2)
  end
}
....
f.tooltip(
   pointFormat: "<span style='color:{series.color}'>{series.name}</span>: <b>{point.y} h</b><br/>",
   split: true
)

I have tried to set point.y / 60 and point.y % 60 but no have effects.

How can I solve? Thanks in advance.

Ruby Nested transaction: will transaction inside will roll back if transaction outside is rolled back?

model1.rb
def method1
   Model1.transaction do
      model2_ref_obj = Model2.find(some_id)
      model2_ref_obj.method1
  end
end


model2.rb
def method1
   Model2.transaction do
   ## so some work
   self.save!
   end
end

However, due to some issue, model1's transaction rollback, will inner transaction will also roll-back.

Ruby Nested transaction: will nested transaction roll back if outside transaction is rolled back?

model1.rb
def method1
   Model1.transaction do
      model2_ref_obj = Model2.find(some_id)
      model2_ref_obj.method1
  end
end


model2.rb
def method1
   Model2.transaction do
   ## so some work
   self.save!
   end
end

However, due to some issue, model1's transaction rollback, will inner transaction will also roll-back.

ArgumentError: undefined class/module Model::FriendlyIdActiveRecordRelation

I have implemented Redis cache for my application data caching. When I try to use cache in my local machine and try to fetch data from cache I get following error : ArgumentError: undefined class/module User::FriendlyIdActiveRecordRelation

After searching google I find that when we fetch from cache it coverts object to our model type. So we need to load all the models in application when we start server (just like happening in production environment). I have created initializer to do that. But still it is not working. What can be the work around to solve this in development environment ?

Thank you.

lundi 22 octobre 2018

how to find the row with maximum number of 1s in a matrix in ruby?

I have a matrix boolean 2D array and i want to find the the row with maximum number of 1s.

require 'matrix'
 m1 = Matrix[[0,1,1,1],[0,0,1,1],[1,1,1,1],[0,0,0,0]]
print m1 

can anyone help me out

vendredi 19 octobre 2018

What is Faraday why use over Ajax

Can anyone help me understand why do we request the API with FARADAY why not use AJAX ?? If we using Faraday what is the advantage over Ajax ?

I'm new to rails apologize if it is a basic question.

jeudi 18 octobre 2018

How to pass changed values from text_field_tag to the controller

My view file:

<% @result.each do |singleAttr| %> <!-- Now the singleAttr is a hash -->
<%= form_tag(change_policy_attr_values_path(singleAttr)) do %>
<tr class="<%= cycle('even', 'odd') %>">
<td><%= label_tag(:attrId,singleAttr["attrId"]) %></td>
<td><%= label_tag(:name,singleAttr["name"]) %></td>
<td style="word-break: break-all;"><%= text_field_tag(:value,singleAttr['value']) %></td>
<td style="text-align: center;">
    <%= submit_tag('Update',:id => "update_button") %> 
</td>
</tr>
<% end %>
<% end %>

Controller file:

def change
  attribValue = params[:value]
  render text: attribValue
end

When i change the value in the text_field_tag and after clicking on update submit button, i am getting the old value. How can i pass the updated text to the controller ?

This is what i am getting in the URL:

http://localhost:3000/policy_attr_values/change?attrId=10&name=MAX_LOCAL_MASK_LENGTH&value=18

I changed the value to 17 in the textbox, but still it's taking 18

Any help?

Thanks,

RailsConfig gem not working as expected in development environment

I have the following setup:

app_dir/config/settings/development.yml dev_setting_1: "hello_dev"

app_dir/config/settings/production.yml prod_setting_1: "hello_prod"

app_dir/config/settings.yml gen_setting_1: "hello_world"

app_dir/config/settings.local.yml local_setting_1: "hello_local"

When I run production env

DISABLE_SPRING=true rails c production

Settings.reload!

Settings.keys

I get expected results:

[:local_setting_1:, gen_setting_1, :prod_setting_1]

HOWEVER

When I run development env DISABLE_SPRING=true rails c development

Settings.reload!

Settings.keys

I only get keys for .local.yml files [:local_setting_1]

I would have expected

[:local_setting_1:, gen_setting_1, :dev_setting_1]

Any thoughts would be much appreciated

I'm running Rails 5.0.6 on a Mac

Skip uniqueness validation for nil class Rails 3

Currently I can't create empty field with nil value, because nil counts as unique. I want to do if field have value then it must be unique, if nil then not and also it can't return empty string value.

This is my validation:

validates :subdomain, :allow_nil => true, uniqueness: true

Rspec: Test an exception which is not handled

In my public method #recalculate, calling the private method1. This method throw exception 'StandardError'. I want to test this scenario, however getting an error.

Note: Don't want to handle an exception.

def recalculate
  method_1
end

private
def method_1
    ## do some calculation
    raise StandardError.new("Test")
end

Rspec Test case:

  it "Test" do
    expect { @product.recalculate.recalculate }.to raise_error(StandardError)
    @product.recalculate
  end

1) Product.Test 
  Failure/Error: @product.recalculate
   StandardError:
     Test
   (required)>'

Finished in 1.39 seconds 1 example, 1 failure

mercredi 17 octobre 2018

In Rails, how to respond_to irrelevant non-http requests?

I have a relatively large website, and all day everyday it gets hit with requests that are irrelevant from all sorts of IP addresses. A common one is example.com/home.zip.

This hits my Home controller, index action {"controller"=>"home", "action"=>"index", "format"=>"zip"}. Currently, it causes a 500 error:

Missing template home/index, application/index with {:locale=>[:en], :formats=>[:zip], :handlers=>[:erb, :builder, :arb]}

I imagine the graceful way of handling it is a 404. The closest I've come to a solution is this:

respond_to do |format|
  format.html
  format.any { redirect_to :foo }
end

Except of redirect_to :foo I would do render file: "#{Rails.root}/public/404.html", status: 404. Am I on the right track?

mardi 16 octobre 2018

how to solve rails server problem in ruby on rails?

I am running the rails server then I am facing the error like this.How to solve it?

enter image description here

Thanks in Advance.

Add Default Value to datatype Array in Rails migration

I was trying to create a field which is datatype of Array through migration and it did got updated in schema.rb file.

However my main goal was to give fixed value to this field (i-e Array) which is not going to change in future. Kinda static value.

I applied this method to create a field.

rails generate migration Store_detailsToAdmin store_details:string

Admin.rb file.

serialize :store_details, Array

rake db:migrate

Can anyone help me out to have default and fixed value to this column. Any help would really be appreciated. Just a heads up i'm very new to rails world. Apologize in advance.

Is Rails version 3.1.1 compatible with Ruby version 2.3?

I am in a situation where I need to update several API-connected gems that are no longer supported by my current version of Ruby. (1.9.3) The Rails release notes for Rails version 3.1.1 state that Rails 3.1 requires Ruby 1.8.7 or higher but it's hard to tell if that includes versions of Ruby which might have been updated more recently than the release notes.

Am I good to update to 2.3 on my Rails 3.1.1 app?

How to add cloudinary file as email attachment in ActionMailer

I am building a job application in Rails and I need to attach resumes(cv) that are uploaded in a job application as an email attachment. All files in the application are uploaded to Cloudinary using CarrierWave. Emails are handled by Action Mailer. In ActionMailer, I have

  class ApplicantMailer < ApplicationMailer    
      def applicant_info(applicant)
        @applicant = applicant
        mail(to: @applicant.job.email, subject: 'Applicant Details')
      end
   end

In my mailer view template, I have

<p>Hi Recruiter, in this email, you would find the resume of the latest applicant</p>
<p>Resume: <%= cl_image_tag(@applicant.resume, :attachment=>true) %></p>

At the moment, this does not render the cloudinary file as an attachment in the email. I need to be able to render the resume as a readable attachment file.

How to handle user equal nil when it is not detected by ActiveRecord::RecordNotFound

I am learning programming only, Ruby on Rails in particular. The problem I face currently is that I doubt in which way to handle my issue is better regarding clean code and avoiding my code smells or probably something else.

So basically, I have users_controller where I check if my jwt is valid: I decode it, withdraw user_id and look for the user in DB by her id.

 def login
    user = decoded_user(permitted_params[:jwt])
    render json: user
  rescue ActiveRecord::RecordNotFound, JWT::DecodeError
    render status: 401, json: { error: 'invalid token' }.to_json
  end

As you can see, in case of invalid jwt or user is not found, it must render 401 error, but somehow when user is nil, rescue ActiveRecord::RecordNotFound does not detect it and render 200 status when I want it 401. When jwt is valid or empty, it all works fine.

I was thinking to wrap it into if else block in case of nil though to me it does not seem really skilled. Could you help me to refactor, please? Thanks!

How can I integrate react with ruby on rails 3.22 version?

I want to convert some of my rails views to react. I have tried with react on rails gem and it says it supports rails 3.x version but it uses webpacker which supports only rails 4.2+ version. I also checked react-rails but that also use webpacker gem. So cant use that as well.

Please let me know if you require any more info from my side.

lundi 15 octobre 2018

Rails: Locales using form_with?

How do I use locales and form_with? By locale I mean /en instead of /?locale=en.

This is part of my view file:

<%= form_with(model: @model, local: true, locale: I18n.locale) do |form| %>

After submitting the form I get the following error:

No route matches {:action=>"show", :controller=>"model_name", :format=>nil, :locale=>#<ModelName id: 2, created_at: "2018-10-15 11:07:36", updated_at: "2018-10-15 11:08:09">}, missing required keys: [:id], possible unmatched constraints: [:locale]

Notice how locale is set with the given model ...

This is my routes.rb:

root 'model_name#new'

scope ':locale', locale: /[a-z]{2}/ do
  root 'model_name#new'
  resources :model_name, only: [:create, :show]
end

I don't understand why I need to set root twice but ...

Thanks!

Retain form data on error in json response Rails

I want to retain form data after an error. I can't use render :new due to json response. what should I do here to retain my data. Thanks in advance.

Here is my code in create action.

@invoice = Invoice.new(invoice_params)
total = []
@invoice.line_items.each do |inv|
  total.push(inv.amount.to_i - inv.get_discount)
  if params[:invoice][:pharmacy].present? || inv.category == 'Pharmacy'
    item = Item.find_by_id(inv.item_id)
    if item.present?
      available_item_stock =  item.available_stock
      if available_item_stock.present?
        if available_item_stock.to_i <= 0 || inv.quantity > available_item_stock.to_i
          if inv.category == 'Pharmacy'
            if params[:invoice][:bed_id].present?
              bed = Bed.where(id: params[:invoice][:bed_id]).first
            end
            msg = { :status => "error", :inventory_path => bed_action_admin_beds_path(bed) }
            flash[:notice] = "Invoice couldn't be saved, because #{item.item_name} has no available stock"
            render :json => msg
          else
            msg = { :status => "error", :inventory_path => new_admin_invoice_path(:type => "inventory",:status => "pharmacy") }
            flash[:notice] = "Invoice couldn't be saved, because #{item.item_name} has no available stock"
            render :json => msg
          end
          return
        end
      end
    end
  end

Ruby: Maximum Waiting time for pessimistic lock?

Two different systems/process try to update same request. However, I am using pessimistic locking mechanism: lock!. Suppose system-1 acquire the lock before system-2. What is maximum waiting time for the system-2 to acquire lock? Related question: If it reached the maximum waiting time, will it rollback transaction?

Request.transaction do

  lock!
    # Do something important

end

dimanche 14 octobre 2018

Ruby on Rails - user session login

I'm getting syntax error, unexpected '=', expecting keyword_end (session [:user_id]) = user.id ^ and syntax error, unexpected '=', expecting keyword_end session [:user_id] = user.id

 class SessionsController < ApplicationController
      def new
      end

      def create
          user = User.find_by(email: params[:session][:email])
          if user && user.authenticate(params[:session][:password])

              session [:user_id] = user.id
              redirect_to user
           else
              flash.now[:error] = 'Bad email/pwd combo. do again'
              render 'new'

           end 


       end

       def destroy
           session.delete(:user_id)
           @current_user = nil
           redirect_to site_home_path
        end 
end

vendredi 12 octobre 2018

Best way to learn ruby/ruby on rails

im decently new to ruby/rails so what method would people recommend for learning ruby on rails

Incorrect MySQL client library version! in RoR

I am getting this error while starting unicorn porcess in RoR.

I, [2018-10-12T07:37:00.285813 #32324]  INFO -- : Refreshing Gem list
Bundler::GemRequireError: There was an error while trying to load the gem 'mysql2'.
Gem Load Error is: Incorrect MySQL client library version! This gem was compiled for 5.1.73 but the client library is 5.5.52-MariaDB.
Backtrace for gem load error is:
/var/www/api2/releases/api2-new/vendor/gems/ruby/2.1.0/gems/mysql2-0.3.15/lib/mysql2.rb:8:in `require'
/var/www/api2/releases/api2-new/vendor/gems/ruby/2.1.0/gems/mysql2-0.3.15/lib/mysql2.rb:8:in `<top (required)>'
/home/svitla/.rvm/gems/ruby-2.1.2@global/gems/bundler-1.14.5/lib/bundler/runtime.rb:91:in `require'
/home/svitla/.rvm/gems/ruby-2.1.2@global/gems/bundler-1.14.5/lib/bundler/runtime.rb:91:in `block (2 levels) in require'
/home/svitla/.rvm/gems/ruby-2.1.2@global/gems/bundler-1.14.5/lib/bundler/runtime.rb:86:in `each'
/home/svitla/.rvm/gems/ruby-2.1.2@global/gems/bundler-1.14.5/lib/bundler/runtime.rb:86:in `block in require'
/home/svitla/.rvm/gems/ruby-2.1.2@global/gems/bundler-1.14.5/lib/bundler/runtime.rb:75:in `each'
/home/svitla/.rvm/gems/ruby-2.1.2@global/gems/bundler-1.14.5/lib/bundler/runtime.rb:75:in `require'
/home/svitla/.rvm/gems/ruby-2.1.2@global/gems/bundler-1.14.5/lib/bundler.rb:107:in `require'

May someone help me on this ?

I don't want to reinstall mysql2 gem to resolve this. Is there any other way to resolve this?

Regards, Vennila K

Ruby: Will pessimist lock (self.lock!) work using update_all?

I don't want to use save! method, will pessimist lock (self.lock!) work using the update_all method?

lock! using save! method.

Account.transaction do
  self.lock!
  account1 = Account.find(...)
  account1.balance -= 100
  account1.save!
end

lock! using update_all method.

Account.transaction do
  self.lock!
  attributes["balance"] = recalculate_balance
  Account.where(:id => self.id).update_all(attributes)
end

Will optimistic locking work for following code using updated_at attribute in update_all?

I want to use optimistic locking for Product model using updated_at. I have implemented the following code for the optimistic lock. There are other ways to implement optimistic locking like using lock_version. However, due to existing code restriction, I am not able to implement using lock_version.

  Product Model

  attr_writer :original_updated_at
  def original_updated_at
    @original_updated_at || updated_at
  end

  def stale_object?
    if self.updated_at > original_updated_at
      @original_updated_at = nil
      return true
    else
      return false
    end
  end

  def public_method
    ##code 
    result = nil
    begin
      result = private_method
      self.original_updated_at = self.updated_at
    rescue ActiveRecord::StaleObjectError => e
      errors.add(:base, ": Following records are changed while you were editing.")
      changes.except("updated_at").each do |name, values|
        errors.add(name, values)
      end
    rescue Exception => error
      ##code
    end
    result
  end



def private_method
    tries = 0
    begin
      raise ActiveRecord::StaleObjectError.new(self, "Product is changed while you were editing") if stale_object?
      attributes = #create hash using some code
      #some code

      attributes["updated_at"] = Time.now.utc
      Product.where(:id => self.id).update_all(attributes)
      self.original_updated_at = self.updated_at
    rescue ActiveRecord::StaleObjectError => e
      if tries < MAX_RETRIES
        tries += 1
        sleep(1 + tries)
        self.reload
        retry
      else
        raise ActiveRecord::StaleObjectError.new(self, "Product is changed while you were editing")
      end
    end
    attributes
  end

mercredi 10 octobre 2018

API formation for side loading only required associated data to ember data

Please check my previous question EMBER JS - Fetch associated model data from back-end only when required Related to the above question I need help on API formation in ruby on rails(JSON format: jsonapi.org) how to form the API for sideloading only students.records and link with data already available in ember-data store (school and students)

Rails 3.2, SQL NoMethodError: undefined method `auth_group='

Full Error Message

1) AuthGroupResourceUser Validations has a valid factory
 Failure/Error: expect(FactoryGirl.build(:auth_group_resource_user)).to be_valid

 NoMethodError:
   undefined method `auth_group=' for #<AuthGroupResourceUser:0x007f929be173c0>
 # /Users/daniel.pan/.rvm/gems/ruby-2.1.2@ssui/gems/factory_girl-4.7.0/lib/factory_girl/attribute_assigner.rb:16:in `public_send'
 # /Users/daniel.pan/.rvm/gems/ruby-2.1.2@ssui/gems/factory_girl-4.7.0/lib/factory_girl/attribute_assigner.rb:16:in `block (2 levels) in object'
 # /Users/daniel.pan/.rvm/gems/ruby-2.1.2@ssui/gems/factory_girl-4.7.0/lib/factory_girl/attribute_assigner.rb:15:in `each'
 # /Users/daniel.pan/.rvm/gems/ruby-2.1.2@ssui/gems/factory_girl-4.7.0/lib/factory_girl/attribute_assigner.rb:15:in `block in object'
 # /Users/daniel.pan/.rvm/gems/ruby-2.1.2@ssui/gems/factory_girl-4.7.0/lib/factory_girl/attribute_assigner.rb:14:in `tap'
 # /Users/daniel.pan/.rvm/gems/ruby-2.1.2@ssui/gems/factory_girl-4.7.0/lib/factory_girl/attribute_assigner.rb:14:in `object'
 # /Users/daniel.pan/.rvm/gems/ruby-2.1.2@ssui/gems/factory_girl-4.7.0/lib/factory_girl/evaluation.rb:12:in `object'
 # /Users/daniel.pan/.rvm/gems/ruby-2.1.2@ssui/gems/factory_girl-4.7.0/lib/factory_girl/strategy/build.rb:9:in `result'
 # /Users/daniel.pan/.rvm/gems/ruby-2.1.2@ssui/gems/factory_girl-4.7.0/lib/factory_girl/factory.rb:42:in `run'
 # /Users/daniel.pan/.rvm/gems/ruby-2.1.2@ssui/gems/factory_girl-4.7.0/lib/factory_girl/factory_runner.rb:29:in `block in run'
 # /Users/daniel.pan/.rvm/gems/ruby-2.1.2@ssui/gems/factory_girl-4.7.0/lib/factory_girl/factory_runner.rb:28:in `run'
 # /Users/daniel.pan/.rvm/gems/ruby-2.1.2@ssui/gems/factory_girl-4.7.0/lib/factory_girl/strategy_syntax_method_registrar.rb:20:in `block in define_singular_strategy_method'
 # ./spec/models/auth_group_resource_user_spec.rb:12:in `block (3 levels) in <top (required)>'

So I am making some unit tests for my model 'auth_group_resource_user'. It belongs to 'auth_group', and either 'user' or 'auth_role' but not both.

auth_roles sql table

CREATE TABLE IF NOT EXISTS `test`.`auth_roles` (
  `id`  INT(11)      NOT NULL     AUTO_INCREMENT,
  `name`VARCHAR(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
)
DEFAULT CHARSET = utf8mb4
COLLATE = utf8mb4_unicode_ci;

auth_groups sql table

CREATE TABLE IF NOT EXISTS `test`.`auth_groups` (
  `id`   INT(11) NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
)
DEFAULT CHARSET = utf8mb4
COLLATE = utf8mb4_unicode_ci;

auth_group_resource_user sql table

CREATE TABLE IF NOT EXISTS `test`.`auth_group_resource_users` (
  `id`            INT(11)   NOT NULL AUTO_INCREMENT,
  `auth_group_id` INT(11)   NOT NULL,
  `user_id`       INT(11)   DEFAULT NULL,
  `auth_role_id`  INT(11)   DEFAULT NULL,
  PRIMARY KEY (`id`),
  CONSTRAINT `auth_group_resource_users_auth_group_id_fk` FOREIGN KEY 
  (`auth_group_id`) REFERENCES `auth_groups` (`id`),
  CONSTRAINT `auth_group_resource_users_user_id_fk` FOREIGN KEY 
  (`user_id`) 
  REFERENCES `users` (`id`),
  CONSTRAINT `auth_group_resource_users_auth_role_id_fk` FOREIGN KEY 
  (`auth_role_id`) REFERENCES `auth_roles` (`id`),
  CONSTRAINT `user_role_check_null` 
  CHECK (
        (`user_id` IS NOT NULL AND `auth_role_id` IS NULL)
    OR  (`user_id` IS NULL AND `auth_role_id` IS NOT NULL))
  )
  DEFAULT CHARSET = utf8mb4
  COLLATE = utf8mb4_unicode_ci;

AuthGroupResourceUser model is:

 class AuthGroupResourceUser < ActiveRecord::Base

   attr_accessible :auth_group_id

   belongs_to :group_resource, polymorphic: true
   belongs_to :authorizations

   validates :auth_group, presence: true
   validates :user_id, presence: true, unless: :auth_role_id
   validates :auth_role_id, presence: true, unless: :user_id

 end

and the factory is:

 FactoryGirl.define do
   factory :auth_group_resource_user do
     auth_group
     user
   end
 end

auth_group factory looks like

 FactoryGirl.define do
   factory :auth_group do
     name { Faker::Internet.user_name(9) }
   end
 end

For the life of me, I cannot figure out why I'm getting the error above.

How to recreate issue: Mysql2::Error: Illegal mix of collations (latin1_swedish_ci,IMPLICIT)

Can anyone suggest how to recreate issue Mysql2::Error: Illegal mix of collations (latin1_swedish_ci,IMPLICIT)

This was triggered due API /admin/products and "action"=>"index".

Error:

/admin/products#GET params: { "controller"=>"admin/products"}, 
exception: ActiveRecord::StatementInvalid, message: Mysql2::Error:
 Illegal mix of collations (latin1_swedish_ci,IMPLICIT) and 
(utf8_general_ci,COERCIBLE) for operation 'like'

mardi 9 octobre 2018

how to upgrade from ruby 2.2.6 to 2.3.0

I have installed rails installer which have rails 5.0.7 and ruby 2.2.6.Now i want to install "Capybara" gem which requires at least ruby 2.3.0.How can i upgrade ruby version from 2.2.6 to 2.3.0?

Rails 5, scope with agregation

I have two models, product and image. Product has many images. Each iemage has position field with number.

 Product
 id | name
 1  | Car

Image 
id| product_id| file_name | position
1 | 1         | asdad.jpg | 1
1 | 1         | asda.jpg  | 2

How to create scope to one image with trhe lowest position number?

scope :main_image, -> { ??? }

And than:

@product.main_image.image.url

Regards Sssebaa

How to speed up active record in rails3.2? My active record is taking more than 3 minutes for querying

This is my active record query for loading accounts with respect to branch,area and mandal.Could anyone help me for optimizing it?

 HpEntry.includes(:area, :mandal, :branch)
        .where(:BranchId => 58, :AreaId => 117, :MandalId => 741)
        .last

How to set RPC timeout in thrift ruby client?

I'm writing python client using thrift, but I can't find any available option to set rpc time out. I am using the default thrift gem, with version 0.10.0

My client code goes below:

t_http_client_transport  = Thrift::HTTPClientTransport.new(BASE_URI + API_END_POINT)
t_json_protocol          = Thrift::JsonProtocol.new(t_http_client_transport)
t_ordering_service_client = TOrderingService::Client.new(t_json_protocol)
t_http_client_transport.open()

Error Permission denied - /usr/local/rvm/gems/ruby-1.9.3-p484@global/extensions/x86_64-linux/1.9.1/bson_ext-1.11.1 (Errno::EACCES)

My rails application could not be started and looking into apache error log I found following. The application is running on apache passenger module. can anyone know how to solve this issue?

[ 2018-10-09 01:12:17.3443 12649/7f5664cc7700 agents/HelperAgent/RequestHandler.h:2060 ]: [Client 20] Cannot checkout session. Error page: Permission denied - /usr/local/rvm/gems/ruby-1.9.3-p484@global/extensions/x86_64-linux/1.9.1/bson_ext-1.11.1 (Errno::EACCES) /usr/local/rvm/rubies/ruby-1.9.3-p484/lib/ruby/1.9.1/fileutils.rb:247:in mkdir' /usr/local/rvm/rubies/ruby-1.9.3-p484/lib/ruby/1.9.1/fileutils.rb:247:infu_mkdir' /usr/local/rvm/rubies/ruby-1.9.3-p484/lib/ruby/1.9.1/fileutils.rb:221:in block (2 levels) in mkdir_p' /usr/local/rvm/rubies/ruby-1.9.3-p484/lib/ruby/1.9.1/fileutils.rb:219:inreverse_each' /usr/local/rvm/rubies/ruby-1.9.3-p484/lib/ruby/1.9.1/fileutils.rb:219:in block in mkdir_p' /usr/local/rvm/rubies/ruby-1.9.3-p484/lib/ruby/1.9.1/fileutils.rb:205:ineach' /usr/local/rvm/rubies/ruby-1.9.3-p484/lib/ruby/1.9.1/fileutils.rb:205:in mkdir_p' /usr/local/rvm/rubies/ruby-1.9.3-p484/lib/ruby/site_ruby/1.9.1/rubygems/ext/builder.rb:210:inwrite_gem_make

lundi 8 octobre 2018

Ruby function for putting string in parentheses

Is there any ruby function that can do the following

str = ' ( '.concat( str.concat( ' ) ' ))

It is placing parentheses on both sides of the string str

Form tag is appearing as a div

I don't know how else to describe this problem. Let me show you the code:

This is my .html.erb file:

    <div class="tab-search-browse">
      <%= form_tag category_searches_path, :id => "#{prefix}-category-search-form" do %>
        <%= label_tag :category_search_terms, t(:category_keywords) %>
        <%= text_field_tag :category_search_terms %>
        <%= submit_tag t(:search_categories), :class => "button utility-button" %>
        <%= content_tag(:span, '* '+t(:enter_category_search_terms), :class => 'instruction') %>
      <% end %>
    </div>

And this is what I see when I view-source:

  <div class="tab-search-browse">
      <form accept-charset="UTF-8" action="/category_searches" id="product-category-search-form" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;" /><input name="authenticity_token" type="hidden" value="pSzNhg22JRKW+qN01fACKb1UURn/BI6wjHtXyYoARvE=" /></div>
        <label for="category_search_terms">Category keywords:</label>
        <input id="category_search_terms" name="category_search_terms" type="text" />
        <input class="button utility-button" name="commit" type="submit" value="Search Categories" />
        <span class="instruction">* Enter keywords related to your item to get category suggestions</span>
      </form>        
  </div>

Looks good, right?

And yet.. what I see in the Chrome Developer Tools, under "Elements" is this:

    <div class="tab-search-browse">
      <div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓"><input name="authenticity_token" type="hidden" value="pSzNhg22JRKW+qN01fACKb1UURn/BI6wjHtXyYoARvE="></div>
        <label for="category_search_terms">Category keywords:</label>
        <input id="category_search_terms" name="category_search_terms" type="text">
        <input class="button utility-button" name="commit" type="submit" value="Search Categories">
        <span class="instruction">* Enter keywords related to your item to get category suggestions</span>
    </div>

Clicking on the submit button does nothing. So I'm inclined to agree with whatever's in the developer tools, rather than the source code. This isn't the first time I've run into this issue, and I'm very confused.

My rails application is not getting started

My rails application is running with ruby-1.9.3-p374 and rails 3.2.21. I am using rvm to manage the ruby versions. Currently, the application is running on Apache + passenger and in the configuration, I have properly set the path for the current ruby and gems however when I am loading application in the browser I am getting following error were application could not be started due to wrong ruby hem path. I am totally clued less where is the issue?

**Web application could not be started**

Permission denied - /usr/local/rvm/gems/ruby-1.9.3-p484@global/extensions/x86_64-linux/1.9.1/bson_ext-1.11.1 (Errno::EACCES)

/usr/local/rvm/rubies/ruby-1.9.3-p484/lib/ruby/1.9.1/fileutils.rb:247:in mkdir' /usr/local/rvm/rubies/ruby-1.9.3-p484/lib/ruby/1.9.1/fileutils.rb:247:infu_mkdir' /usr/local/rvm/rubies/ruby-1.9.3-p484/lib/ruby/1.9.1/fileutils.rb:221:in block (2 levels) in mkdir_p' /usr/local/rvm/rubies/ruby-1.9.3-p484/lib/ruby/1.9.1/fileutils.rb:219:inreverse_each' /usr/local/rvm/rubies/ruby-1.9.3-p484/lib/ruby/1.9.1/fileutils.rb:219:in block in mkdir_p' /usr/local/rvm/rubies/ruby-1.9.3-p484/lib/ruby/1.9.1/fileutils.rb:205:ineach' /usr/local/rvm/rubies/ruby-1.9.3-p484/lib/ruby/1.9.1/fileutils.rb:205:in mkdir_p' /usr/local/rvm/rubies/ruby-1.9.3-p484/lib/ruby/site_ruby/1.9.1/rubygems/ext/builder.rb:210:inwrite_gem_make_out' /usr/local/rvm/rubies/ruby-1.9.3-p484/lib/ruby/site_ruby/1.9.1/rubygems/ext/builder.rb:132:in build_error' /usr/local/rvm/rubies/ruby-1.9.3-p484/lib/ruby/site_ruby/1.9.1/rubygems/ext/builder.rb:171:inrescue in build_extension' /usr/local/rvm/rubies/ruby-1.9.3-p484/lib/ruby/site_ruby/1.9.1/rubygems/ext/builder.rb:156:in build_extension' /usr/local/rvm/rubies/ruby-1.9.3-p484/lib/ruby/site_ruby/1.9.1/rubygems/ext/builder.rb:198:inblock in build_extensions' /usr/local/rvm/rubies/ruby-1.9.3-p484/lib/ruby/site_ruby/1.9.1/rubygems/ext/builder.rb:195:in each' /usr/local/rvm/rubies/ruby-1.9.3-p484/lib/ruby/site_ruby/1.9.1/rubygems/ext/builder.rb:195:inbuild_extensions' /usr/local/rvm/rubies/ruby-1.9.3-p484/lib/ruby/site_ruby/1.9.1/rubygems/specification.rb:1436:in block in build_extensions' /usr/local/rvm/rubies/ruby-1.9.3-p484/lib/ruby/site_ruby/1.9.1/rubygems/user_interaction.rb:45:inuse_ui' /usr/local/rvm/rubies/ruby-1.9.3-p484/lib/ruby/site_ruby/1.9.1/rubygems/specification.rb:1434:in build_extensions' /usr/local/rvm/rubies/ruby-1.9.3-p484/lib/ruby/site_ruby/1.9.1/rubygems/stub_specification.rb:60:inbuild_extensions' /usr/local/rvm/rubies/ruby-1.9.3-p484/lib/ruby/site_ruby/1.9.1/rubygems/basic_specification.rb:56:in contains_requirable_file?' /usr/local/rvm/rubies/ruby-1.9.3-p484/lib/ruby/site_ruby/1.9.1/rubygems/specification.rb:925:inblock in find_inactive_by_path' /usr/local/rvm/rubies/ruby-1.9.3-p484/lib/ruby/site_ruby/1.9.1/rubygems/specification.rb:924:in each' /usr/local/rvm/rubies/ruby-1.9.3-p484/lib/ruby/site_ruby/1.9.1/rubygems/specification.rb:924:infind' /usr/local/rvm/rubies/ruby-1.9.3-p484/lib/ruby/site_ruby/1.9.1/rubygems/specification.rb:924:in find_inactive_by_path' /usr/local/rvm/rubies/ruby-1.9.3-p484/lib/ruby/site_ruby/1.9.1/rubygems.rb:185:intry_activate' /usr/local/rvm/rubies/ruby-1.9.3-p484/lib/ruby/site_ruby/1.9.1/rubygems/core_ext/kernel_require.rb:132:in rescue in require' /usr/local/rvm/rubies/ruby-1.9.3-p484/lib/ruby/site_ruby/1.9.1/rubygems/core_ext/kernel_require.rb:144:inrequire' /usr/local/rvm/gems/ruby-1.9.3-p484@httpd24/gems/passenger-4.0.29/lib/phusion_passenger/loader_shared_helpers.rb:219:in block in run_load_path_setup_code' /usr/local/rvm/gems/ruby-1.9.3-p484@httpd24/gems/passenger-4.0.29/lib/phusion_passenger/loader_shared_helpers.rb:333:inrunning_bundler' /usr/local/rvm/gems/ruby-1.9.3-p484@httpd24/gems/passenger-4.0.29/lib/phusion_passenger/loader_shared_helpers.rb:217:in run_load_path_setup_code' /usr/local/rvm/gems/ruby-1.9.3-p484@httpd24/gems/passenger-4.0.29/helper-scripts/rack-preloader.rb:96:inpreload_app' /usr/local/rvm/gems/ruby-1.9.3-p484@httpd24/gems/passenger-4.0.29/helper-scripts/rack-preloader.rb:153:in <module:App>' /usr/local/rvm/gems/ruby-1.9.3-p484@httpd24/gems/passenger-4.0.29/helper-scripts/rack-preloader.rb:29:in' /usr/local/rvm/gems/ruby-1.9.3-p484@httpd24/gems/passenger-4.0.29/helper-scripts/rack-preloader.rb:28:in `' Application root /home/sunny.bogawat/work/viewpoint Environment (value of RAILS_ENV, RACK_ENV, WSGI_ENV and PASSENGER_ENV) development Ruby interpreter command /usr/local/rvm/wrappers/ruby-1.9.3-p484@httpd24/ruby User and groups uid=1354768763(sunny.bogawat) gid=1354768763(sunny.bogawat) groups=1354768763(sunny.bogawat),1354760705(domain users),1354761303(phlnn1),1354761305(phlnn3),1354761334(phlnn5),1354761366(phlnn10v),1354761370(phlnn8),1354762461(sgsengineeringunixlogin),1354762462(sgsengineeringunixadmin),1354762682(hounu1),1354762683(phlnu1),1354762743(isp_admin),1354762792(hounn8),1354762824(enterasys),1354763402(phlnn7),1354763598(hounn3),1354763599(hounn4),1354763600(hounn7),1354763768(phlnn95),1354763783(cltnn1),1354763898(network managed services),1354763932(phlnn110),1354764283(ca_network mgd svcs users),1354764438(phlnn13),1354764596(ca_users),1354764708(phlnn232v),1354765654(phlnn155),1354767326(phl2samdwmgt02),1354767568(phlnn272v),1354767638(phlnu415v_admins),1354767900(sungard.tools.resource.na),1354768008(phlnn275),1354768074(aurnu1v),1354768350(phlnn188),1354771880(hounn9v),1354772363(hounn7v),1354772364(hounn8v),1354772933(phlnn232vs),1354773379(phlnn155vs),1354773807(phlnu576v_admins),1354775321(permit members to log on to the server phlnu1vs),1354777329(phlnn493v_admins),1354777330(phlnn493v),1354777951(centrify_sftp_users)

bundler problem rails app isn't deploying to heroku

i tried deploying my rails app on heroku from github and also from my terminal but i got this error

-----> Ruby app detected
-----> Compiling Ruby/Rails
 !
 !     There was an error parsing your Gemfile, we cannot continue
 !     Warning: the running version of Bundler (1.15.2) is older than the version that created the lockfile (1.16.5). We suggest you upgrade to the latest version of Bundler by running `gem install bundler`.
 !     The path `/tmp/spree_simple_sales` does not exist.
 !
 !     Push rejected, failed to compile Ruby app.
 !     Push failed

this is my gemfile.lock file

RUBY VERSION
   ruby 2.5.1p57

BUNDLED WITH
   1.16.5

i dong know why it is still giving me bundler problem, how can i fix it please.

dimanche 7 octobre 2018

Continue script after rescue in ruby

I am parsing JSON output by using the curl mentioned below , However I am getting no method error while parsing the output due to DESCRIPTION #{h["incident_updates"][1]["status"] . because [["incident_updates"][1][status]] is not present in some cases, only the values of [["incident_updates"][0][status]] is available .

( But others iteration contains values for both [0][status] [1][status] )

So to avoid the error used rescue method ,however error is prevented but script is not executing after the first error(iteration stopped on first error itself, script is not continuing ) . Need to run the script till the iteration completes (i.e., though no values present for [1] [status] script should run to bring the value for next iteration element because next element may contain [1] [status]) Please help on this . Thanks in advance

def inc
begin
        page3 = `curl https://api.statuspage.io/v1/pages/incidents.json?page=3 -H "Authorization: OAuth a8ef42"`
JSON.parse(page3).each do |h|
        puts "ID : #{h["id"]} , CREATED AT : #{h["created_at"]} , LINK : #{h["shortlink"]} , ISSUE NAME : #{h["name"]} , DESCRIPTION #{h["incident_updates"][0]["status"]} , DESCRIPTION #{h["incident_updates"][1]["status"]}"
end
rescue NoMethodError => e
end
end

Rspec: How to test an exception is raised in private method?

Getting error while testing an exception in a private method. Please suggest How to test an exception is raised in private method which is called from a public method.

Public

def public_method
    private_method
end

Private

  def private_method
    tries = 0
    begin
      raise Product::StaleObjectError.new("Product is changed while you were editing") if stale_object?
      // Do some work
      raise Exception.new("Total amount used is greater than approved") if total_approved < 0

      // Save Product
    rescue Product::StaleObjectError => e
      if tries < MAX_RETRIES
        tries += 1
        sleep(1 + tries)
        reload
        retry
      else
        raise Product::StaleObjectError("Product is changed while you were editing")
      end
    end
    attributes
  end

Test Case:

  before(:each) do
    @prod_v1 = Product.new
  end
  it 'if product stale, then an exception should raise' do
    Product.any_instance.stub(:stale_object?).and_return(true)
    expect_any_instance_of(Product).to receive(:private_method).and_raise(Product::StaleObjectError.new("Product is changed while you were editing"), nil)
    @prod_v1.public_method
  end

I am getting following error for test case

 Failure/Error: @product_v1.private_method
 Product::StaleObjectError:
   Product is changed while you were editing
 # ./app/models/product.rb:10:in `recalculate_total_amount_used'
 # ./spec/models/product_spec.rb:67:in `block (4 levels) in <top (required)>'

Rspec: Getting error while testing private method

Getting error while testing a private method. Please suggest how to test private method is called from a public method.

Public

def public_method
    private_method
end

Private

  def private_method
    tries = 0
    begin
      raise Product::StaleObjectError.new("Product is changed while you were editing") if stale_object?
      // Do some work
      raise Exception.new("Total amount used is greater than approved") if total_approved < 0

      // Save Product
    rescue Product::StaleObjectError => e
      if tries < MAX_RETRIES
        tries += 1
        sleep(1 + tries)
        reload
        retry
      else
        raise Product::StaleObjectError("Product is changed while you were editing")
      end
    end
    attributes
  end

Test Case:

  before(:each) do
    @prod_v1 = Product.new
  end
  it 'test private method called' do
    expect_any_instance_of {Product}.to receive(:private_method)
    @prod_v1.public_method
  end

I am getting following error for test case

  Failure/Error: expect_any_instance_of {Prod}.to receive(:)
     ArgumentError:
       wrong number of arguments (0 for 1)

samedi 6 octobre 2018

Ruby: Right way to do optimistic locking?

Context: Product is getting updated by multiple threads. So it leads the race condition. So I am using optimistic locking because it is frequently not updated. For latest update state of the product is determined by updated_at attribute.

For example, Prod (id=1) is updated at t1 on the machine:1. Same product(id=1) is updated at t2 on the machine:2. Now the state of Prod (id=1) on the machine:1 is stale.

Approach To determine stale: I will compare the value of updated_at on the machine with the store value of updated_atin the database value.

My main concern is setting the value of @original_updated_at. Should I use attr_writer :original_updated_at. Is this right way do optimistic locking.

attr_accessor : :original_updated_at
  def original_updated_at
    @original_updated_at || updated_at.to_f
  end


  def stale_object?
    if updated_at.to_f > original_updated_at.to_f
      @original_updated_at = nil
      return true
    else
      @original_updated_at = updated_at.to_f
      return false
    end
  end

  def recalculate
    tries = 0
    begin
      raise Product::StaleObjectError.new("StaleObjectError") if stale_object?
      attributes["updated_at"] = Time.now.utc
      Product.where(:id => self.id).update_all(attributes)
      self.attributes = attributes
    rescue Product::StaleObjectError => e
      if tries < MAX_RETRIES
        tries += 1
        sleep(1 + tries)
        reload
        retry
      else
        raise Product::StaleObjectError("StaleObjectError")
      end
    end
  end

vendredi 5 octobre 2018

Beginner stuck on Ruby on Rails project "...must exist"

So my assignment asks me to generate a page that handles students, courses, and sections. I'm supposed to be using many_to_many or some similar method to be able to list all this shared data. My specific problem is that I created a new table (rails g scaffold enrollment students:references sections:references) that doesn't seem to work. when I attempt to create a new enrollment using a student and section, I get an error stating that "Section must exist" error . I have no idea where this error is coming from. The sections field in this view is only populated with existing sections, so the fact that it says "must exist" is very...confusing. Can anyone point me in the right direction to solve this? I've rebuilt this project 3 times trying different methods and am just... stuck. I'll post the relevant code, but if I'm wrong about which sections you may need to see, I'll happily post the rest.

class Enrollment < ApplicationRecord
belongs_to :section
belongs_to :student 
end

<%= form_with(model: enrollment, local: true) do |form| %>
<% if enrollment.errors.any? %>
<div id="error_explanation">
  <h2><%= pluralize(enrollment.errors.count, "error") %> 
prohibited this enrollment from being saved:</h2>

  <ul>
  <% enrollment.errors.full_messages.each do |message| %>
    <li><%= message %></li>
  <% end %>
  </ul>
 </div>
 <% end %>

<div class="field">
<%= form.label :student_id %>
<%= form.collection_select :student_id, Student.order(:student_name), :id, 
:student_id, include_blank:true %>
</div>

<div class="field">
<%= form.label :course_id %>
<%= form.collection_select :course_id, Course.order(:name), :id, :name, 
include_blank: true %>
</div>

<div class="field">
<%= form.label :sections_number %>
<%= form.collection_select :section_number, Section.all, :id, 
:section_number, include_blank:false %>
</div>

<div class="actions">
<%= form.submit %>
</div>
<% end %>

class Section < ApplicationRecord
has_many :enrollments
has_and_belongs_to_many :students, through: :enrollments       
belongs_to :course

def numsem
    "#{course.name} #{course_id}"
end
end

Devise gem to check encrypted password with current password

In my Ruby on Rails application, we are using devise gem encryptor module to encrypt the password from login page. My user model has encrypted password and does not store password in raw form. I have password update feature for user and need to enter current password. I need to validate with the encrypted password from user model using devise encryptor module which uses bcrypt and klass . How can I achieve it

jeudi 4 octobre 2018

Ruby: How to test private method?

I have implemented Optimistic Locking for Race Condition. If lock_version doesn't match with the updated lock_version in the database, then it will trigger retry three times. Can you suggest how to test this retry event.

Note: I can't change private method2

Public

def method1
  begin
     method2
  rescue Exception => e

  end
end

Private

  def method2
    tries = 0
    begin
      raise Product::StaleObjectError.new("Product is changed while you were editing") if stale_object?
      // Do some work
      raise Exception.new("Total amount used is greater than approved") if total_approved < 0

      // Save Product
    rescue Product::StaleObjectError => e
      if tries < MAX_RETRIES
        tries += 1
        sleep(1 + tries)
        reload
        retry
      else
        raise Product::StaleObjectError("Product is changed while you were editing")
      end
    end
    attributes
  end

Test Case:

  it 'method1 should call three times if there is stale_object' do
    prod_v1 = Car.find(@car.id)
    prod_v1.stub(:stale_object?).and_return true
    prod_v1.method1
    expect{prod_v1}.to receive(:method2).exactly(3).times
  end

I am getting following error for test case

 Failure/Error: expect{car_v1}.to receive(:method2).exactly(3).times
   (#<Proc:).method2(any args)
       expected: 2 times with any arguments
       received: 0 times with any arguments

Hello.. I am installing rails on my system..Below are problem I am facing after installation

As I open Command Prompt with Ruby and Rails I get following :

"

#Rails Environment Configuration.

C:/RailsInstaller/scripts/config_check.rb:28:in ``': No such file or directory - rails -v (Errno::ENOENT)

    from C:/RailsInstaller/scripts/config_check.rb:28:in `run'
    from C:/RailsInstaller/scripts/config_check.rb:83:in `<main>'

"

If I ignore above error and continue installing bundle and mysql..it also generate few error and after all that .. I am unable to open localhost:3000 due to all error..

Please help me to figure out solution of above error..

Thank you...!

Rspec: How to test retry?

I have implemented Optimistic Locking for Race Condition. If lock_version doesn't match with the updated lock_version in the database, then it will trigger retry three times. Can you suggest how to test this retry event

#Product: Model's new field:
    #  lock_version                       :integer(4)      default(0), not null

def recalculate
  method_1
  self.save!
end

private
def method_1
    begin
      ####
      ####
      if self.lock_version == Product.find(self.id).lock_version
         Product.where(:id => self.id).update_all(attributes)
      else
         raise ActiveRecord::StaleObjectError.new(self, "test")
      end
    rescue ActiveRecord::StaleObjectError => e
        if tries < 3
           tries += 1
           sleep(1 + tries)
           self.reload
           retry
        else
           raise Exception.new(timeout.inspect)
        end
    end
end

Rspec Unit Test:

  it 'if car is updated then ActiveRecord::StaleObjectError should be raised' do
    prod_v1 =Product.find(@prod.id)
    prod_v2 = Car.find(@prod.id)
    prod_v1.recalculate
    prod_v1.reload  # will make lock_version of prod_v1 to 1
    prod_v2.recalculate # howvever lock_version of prod_v2 is still 0.
    expect{car_v2.send(:method1)}.to receive(:retry)
  end

Ruby: Will optimistic locking work using update_all?

I am trying to implement the Optimistic Locking for Race Condition. For that, I added an extra column lock_version in the Product: Model through migration.

#Product: Model's new field:
    #  attribute_1
    #  lock_version                       :integer(4)      default(0), not null
before_validation :method_1, :if => :recalculation_required_attribute

def method_1
    ####
    ####
    if self.lock_version == Product.find(self.id).lock_version
       attributes["lock_version"] += 1
       attributes["updated_at"] = Time.now
       Product.where(:id => self.id).update_all(attributes)
       self.attributes = attributes
    end
end

Product Model has an attribute_1. If recalculation is required for attribute_1 then before_validation: method_1 will call.

I am using optimistic locking using lock_version. However, update_all will not increase the lock_version and can't self.save! because it will trigger the before_validation: method1 for infinite times.

If I do like following will optimistic locking work using update_all?

attributes["lock_version"] = 1 +1
attributes["updated_at"] = Time.now
Product.where(:id => self.id).update_all(attributes)

You can check more information on lock_version

Rspec: How to test an exception which is getting raised in private method?

In my public method #recalculate, calling the private method1. This method throw exception 'ActiveRecord::StaleObjectError'.

def recalculate
  method_1
  self.save!
end

private
def method_1
    begin
      ####
      ####
      if self.lock_version == Product.find(self.id).lock_version
         Product.where(:id => self.id).update_all(attributes)
      else
         raise ActiveRecord::StaleObjectError.new(self, "test")
      end
    rescue ActiveRecord::StaleObjectError => e
        if tries < 3
           tries += 1
           sleep(1 + tries)
           self.reload
           retry
        else
           raise Exception.new(timeout.inspect)
        end
    end
end

Rspec Test case:

  it 'if car is updated then ActiveRecord::StaleObjectError should be raised' do
    prod_v1 =Product.find(@prod.id)
    prod_v2 = Car.find(@prod.id)
    prod_v1.recalculate
    prod_v1.reload  # will make lock_version of prod_v1 to 1

    prod_v2.recalculate # howvever lock_version of prod_v2 is still 0.

    expect(prod_v2.send(:method1)).to raise_error(ActiveRecord::StaleObjectError)

Error:

     Failure/Error: prod_v1.recalculate
 ActiveRecord::StaleObjectError:
   Attempted to Product is changed while you were editing a stale object: Product

Surprisingly, in error, it is showing Failure/Error: prod_v1.recalculate instead of Failure/Error: prod_v2.recalculate

Please suggest how to write the unit test case for an exception which is raised in private method. I have used send based on the link:

mercredi 3 octobre 2018

RSpec: How to raise the exception in private method

I have implemented Optimistic Locking for Race Condition. For that, I added an extra column lock_version in the Product. Method: recalculate is calling private method_1 then it saves (save!) the product. I can't use save! in private method_1, because it will fail the other things. I don't want to restructure the business logic.

#Product: Model's new field:
    #  lock_version                       :integer(4)      default(0), not null

def recalculate
  method_1
  self.save!
end

private
def method_1
    begin
      ####
      ####
      if self.lock_version == Product.find(self.id).lock_version
         Product.where(:id => self.id).update_all(attributes)
      else
         raise ActiveRecord::StaleObjectError.new(self, "test")
      end
    rescue ActiveRecord::StaleObjectError => e
        if tries < 3
           tries += 1
           sleep(1 + tries)
           self.reload
           retry
        else
           raise Exception.new(timeout.inspect)
        end
    end
end

Rspec Test case:

  it 'if car is updated then ActiveRecord::StaleObjectError should be raised' do
    prod_v1 =Product.find(@prod.id)
    prod_v2 = Car.find(@prod.id)
    prod_v1.recalculate
    prod_v1.reload  # will make lock_version of prod_v1 to 1

    prod_v2.recalculate # howvever lock_version of prod_v2 is still 0.

    expect(car_v2).to receive(:method1).and_raise(ActiveRecord::StaleObjectError)
  end

When I try to write above the test case, then it should raise an Exception ActiveRecord::StaleObjectError. However, I am getting an error like

 Failure/Error: expect(car_v2).to receive(:set_total_and_buckets_used).and_raise(ActiveRecord::StaleObjectError)
 ArgumentError:
   wrong number of arguments (0 for 2)

Ruby undefined method `all?' for 8:Fixnum

Trying to to use all with delete if

product.value_changes.delete_if {|k,v| v.all?(&:blank?) }

Ruby: How to handle optimistic locking using update_all(attributes)

I am trying to implement the Optimistic Locking for Race Condition. For that, I added an extra column lock_version in the Product: Model through migration.

#Product: Model's new field:
    #  attribute_1
    #  lock_version                       :integer(4)      default(0), not null
before_validation :method_1, :if => :recalculation_required_attribute

def method_1
    ####
    ####
    if self.lock_version == Product.find(self.id).lock_version
       Product.where(:id => self.id).update_all(attributes)
       self.attributes = attributes
       self.save!
    end
end

Product Model has an attribute_1. If recalculation is required for attribute_1 then before_validation: method_1 will call.

I am using optimistic locking using lock_version. However, update_all will not increase the lock_version. So I start usingsave!. Now I am getting a new error: SystemStackError: stack level too deep because self.save! triggers the before_validation: method1. How to stop infinite loop of call back and handle optimistic locking in the above case.

Ruby before_validation triggers infinite loop of call back

Product Model has an attribute_1. If recalculation is required for attribute_1 then before_validation will call. It giving SystemStackError: stack level too deep because self.save! triggers the before_validation. How to stop infinite loop of call back.

before_validation :method_1, :if => :recalculation_required_attribute

I am using optimistic locking using lock_version. 'update_all' will not increase the lock_version. So I am using save!. It is calling the infinite look of call back.

def method_1
    ####
    ####
    if self.lock_version == Product.find(self.id).lock_version
       Product.where(:id => self.id).update_all(attributes)
       self.attributes = attributes
       self.save!
    end
end

mardi 2 octobre 2018

Parse API output in ruby

Apologies if it is very basic one , completely new to ruby.

Below is the sample response I am getting while using the curl , need to get the values of body , created_at from the below output .

When I tried to check type of the value , puts returns true for (string) and false for hash and array

`#puts value.is_a?(Hash)
#puts value.is_a?(Array)
#puts value.is_a?(String)`

Not sure how to get value from the below output , Please help on with the first step/idea need to do here , will try on and revert back on getting any issues further

SAMPLE CALL curl https://api.statuspage.io/v1/pages/qfn30z5r6s5h/incidents.json \ -H "Authorization: OAuth 2a7b9d4aac30956d537ac76850f4d78de30994703680056cc103862d53cf8074"

SAMPLE RESPONSE
  [
    {
      "created_at": "2013-04-21T11:45:33-06:00",
      "id": "tks5n8x7w24h",
      "impact": "none",
      "impact_override": null,
      "incident_updates": [
        {
          "body": "We will be performing a data layer migration from our existing Postgres system over to our new, multi-region, distributed Riak cluster. The application will be taken offline during the entirety of this migration. We apologize in advance for the inconvenience",
          "created_at": "2013-04-21T11:45:33-06:00",
          "display_at": "2013-04-21T11:45:33-06:00",
          "id": "kb4fpktpqm0l",
          "incident_id": "tks5n8x7w24h",
          "status": "scheduled",
          "twitter_updated_at": null,
          "updated_at": "2013-04-21T11:45:33-06:00",
          "wants_twitter_update": false,
          "affected_components": [
            {
              "code": "ftgks51sfs2d",
              "name": "API",
              "old_status": "operational",
              "new_status": "operational"
            }
          ]
        }
      ],
      "metadata": [
        "jira": {
          "issue_id": "value"
        }
      ],
      "monitoring_at": null,
      "name": "Data Layer Migration",
      "page_id": "jcm87b8scw0b",
      "postmortem_body": null,
      "postmortem_body_last_updated_at": null,
      "postmortem_ignored": true,
      "postmortem_notified_subscribers": false,
      "postmortem_notified_twitter": false,
      "postmortem_published_at": null,
      "resolved_at": null,
      "scheduled_auto_in_progress": false,
      "scheduled_auto_completed": false,
      "scheduled_for": "2013-05-04T01:00:00-06:00",
      "scheduled_remind_prior": false,
      "scheduled_reminded_at": null,
      "scheduled_until": "2013-05-04T03:00:00-06:00",
      "shortlink": "",
      "status": "scheduled",
      "updated_at": "2013-04-21T11:45:33-06:00"
    },
    {
      "created_at": "2013-04-21T11:04:28-06:00",
      "id": "cz46ym8qbvwv",
      "impact": "critical",
      "impact_override": null,
      "incident_updates": [
        {
          "body": "A postmortem analysis has been posted for this incident.",
          "created_at": "2013-04-21T11:42:31-06:00",
          "display_at": "2013-04-21T11:42:31-06:00",
          "id": "dn051mnj579k",
          "incident_id": "cz46ym8qbvwv",
          "status": "postmortem",
          "twitter_updated_at": null,
          "updated_at": "2013-04-21T11:42:31-06:00",
          "wants_twitter_update": false
        },
        {
          "body": "The application has returned to it's normal performance profile. We will be following up with a postmortem about future plans to guard against additional master database failure.",
          "created_at": "2013-04-21T11:16:38-06:00",
          "display_at": "2013-04-21T14:07:00-06:00",
          "id": "ppdqv1grhm64",
          "incident_id": "cz46ym8qbvwv",
          "status": "resolved",
          "twitter_updated_at": null,
          "updated_at": "2013-04-21T11:36:15-06:00",
          "wants_twitter_update": false,
          "affected_components": [
            {
              "code": "ftgks51sfs2d",
              "name": "API",
              "old_status": "degraded_performance",
              "new_status": "operational"
            }
          ]
        },
        {
          "body": "The slave database has been successfully promoted, but is running slow due to a cold query cache. The application is open and available for requests, but should will be performing in a degraded state for the next few hours. We will continue to monitor the situation.",
          "created_at": "2013-04-21T11:14:46-06:00",
          "display_at": "2013-04-21T11:14:46-06:00",
          "id": "j7ql87ktwnys",
          "incident_id": "cz46ym8qbvwv",
          "status": "monitoring",
          "twitter_updated_at": null,
          "updated_at": "2013-04-21T11:14:46-06:00",
          "wants_twitter_update": false,
          "affected_components": [
            {
              "code": "ftgks51sfs2d",
              "name": "API",
              "old_status": "major_outage",
              "new_status": "degraded_performance"
            }
          ]
        },
        {
          "body": "The slave database is 60% through it's recovery process. We will provide another update once the application is back up.",
          "created_at": "2013-04-21T11:08:42-06:00",
          "display_at": "2013-04-21T11:08:42-06:00",
          "id": "xzgd3y9zdzt9",
          "incident_id": "cz46ym8qbvwv",
          "status": "identified",
          "twitter_updated_at": null,
          "updated_at": "2013-04-21T11:08:42-06:00",
          "wants_twitter_update": false,
          "affected_components": [
            {
              "code": "ftgks51sfs2d",
              "name": "API",
              "old_status": "major_outage",
              "new_status": "major_outage"
            }
          ]
        },
        {
          "body": "The master database server could not boot due to a corrupted EBS volume. We are in the process of failing over to the slave database. ETA for the application recovering is 5 minutes.",
          "created_at": "2013-04-21T11:06:27-06:00",
          "display_at": "2013-04-21T11:06:27-06:00",
          "id": "9307nsfg3dxd",
          "incident_id": "cz46ym8qbvwv",
          "status": "identified",
          "twitter_updated_at": null,
          "updated_at": "2013-04-21T11:06:27-06:00",
          "wants_twitter_update": false,
          "affected_components": [
            {
              "code": "ftgks51sfs2d",
              "name": "API",
              "old_status": "major_outage",
              "new_status": "major_outage"
            }
          ]
        },
        {
          "body": "We're investigating an outage with our master database server.",
          "created_at": "2013-04-21T11:04:28-06:00",
          "display_at": "2013-04-21T11:04:28-06:00",
          "id": "dz959yz2nd4l",
          "incident_id": "cz46ym8qbvwv",
          "status": "investigating",
          "twitter_updated_at": null,
          "updated_at": "2013-04-21T11:04:29-06:00",
          "wants_twitter_update": false,
          "affected_components": [
            {
              "code": "ftgks51sfs2d",
              "name": "API",
              "old_status": "operational",
              "new_status": "major_outage"
            }
          ]
        }
      ],
      "metadata": [
        "jira": {
          "issue_id": "value"
        }
      ],
      "monitoring_at": "2013-04-21T11:14:46-06:00",
      "name": "Master Database Failure",
      "page_id": "jcm87b8scw0b",
      "postmortem_body": "##### Issue\r\n\r\nAt approximately 17:02 UTC on 2013-04-21, our master database server unexpectedly went unresponsive to all network traffic. A reboot of the machine at 17:05 UTC resulted in a failed mount of a corrupted EBS volume, and we made the decision at that time to fail over the slave database.\r\n\r\n##### Resolution\r\n\r\nAt 17:12 UTC, the slave database had been successfully promoted to master and the application recovered enough to accept web traffic again. A new slave database node was created and placed into the rotation to guard against future master failures. The promoted slave database performed slowly for the next couple of hours as the query cache began to warm up, and eventually settled into a reasonable performance profile around 20:00 UTC.\r\n\r\n##### Future Mitigation Plans\r\n\r\nOver the past few months, we've been working on an overhaul to our data storage layer with a migration from a Postgres setup to a distributed, fault-tolerant, multi-region data layer using Riak. This initiative has been prioritized, and the migration will be performed in the coming weeks. We will notify our clients of the scheduled downtime via an incident on this status site, and via a blog post.",
      "postmortem_body_last_updated_at": "2013-04-21T17:41:00Z",
      "postmortem_ignored": false,
      "postmortem_notified_subscribers": false,
      "postmortem_notified_twitter": false,
      "postmortem_published_at": "2013-04-21T17:42:31Z",
      "resolved_at": "2013-04-21T14:07:00-06:00",
      "scheduled_auto_in_progress": false,
      "scheduled_auto_completed": false,
      "scheduled_for": null,
      "scheduled_remind_prior": false,
      "scheduled_reminded_at": null,
      "scheduled_until": null,
      "shortlink": "",
      "status": "postmortem",
      "updated_at": "2013-04-21T11:42:31-06:00"
    },
    {
      "created_at": "2013-04-01T12:00:00-06:00",
      "id": "2ggpd60zvx3c",
      "impact": "none",
      "impact_override": null,
      "incident_updates": [
        {
          "body": "At approximately 6:55 PM, our network provider at ServerCo experienced a brief network outage at their New Jersey data center. The network outage lasted approximately 14 minutes, and all web requests during that time were not received. No data was lost, and the system recovered once the network outage at ServerCo was repaired.",
          "created_at": "2013-04-21T11:02:00-06:00",
          "display_at": "2013-04-21T11:02:00-06:00",
          "id": "mkfzp9swbk4z",
          "incident_id": "2ggpd60zvx3c",
          "status": "investigating",
          "twitter_updated_at": null,
          "updated_at": "2013-04-21T11:02:00-06:00",
          "wants_twitter_update": false
        }
      ],
      "metadata": [
        "jira": {
          "issue_id": "value"
        }
      ],
      "monitoring_at": null,
      "name": "Brief Network Outage",
      "page_id": "jcm87b8scw0b",
      "postmortem_body": null,
      "postmortem_body_last_updated_at": null,
      "postmortem_ignored": false,
      "postmortem_notified_subscribers": false,
      "postmortem_notified_twitter": false,
      "postmortem_published_at": null,
      "resolved_at": null,
      "scheduled_auto_in_progress": false,
      "scheduled_auto_completed": false,
      "scheduled_for": null,
      "scheduled_remind_prior": false,
      "scheduled_reminded_at": null,
      "scheduled_until": null,
      "shortlink": "",
      "status": "resolved",
      "updated_at": "2013-04-01T12:00:00-06:00"
    }
  ]

Ruby: Pessimistic locking is not working properly with reload

Pessimistic locking is not working properly with reload (used in the test cases). with_lock and reload is not working correctly test cases are getting failed. If I removed the with_lock then test work fine.

def method_name1
  self.with_lock do
    attributes["amount_used"] = get_total_amount_used
    attributes["updated_at"] = Time.now.utc
    Product.where(:id => self.id).update_all(attributes)
  end
end

I have written unit test cases using FactoryGirl. It calls the method_name1 which recalculate the total after the used amount. If you check the first Test case 1: total = 600 and amount_used = -200 (-ve means reducing), now total should be 400.00. Similarly for "Test case 2", After running "Test case 1" total is 400.00. amount_used = 200 (+ve means add), total should be 600.00. But Test Case 2 is saying 800.00.

context 'description' do
  before(:each) do
    @product.total = 600
    @product.method_name1
  end

  it 'is updated automatically if valid' do
    @product.amount_used = -200
    @product.save
    @product.reload
    should eq('400.0')       #Working
  end

  it 'is not changed if invalid' do
    @product.amount_used = 200
    @product.save
    @product.reload
    should eq('600.0')      #Not Working
  end
end

Error For Test Case 2: Failure/Error: should eq('600.0')

   expected: "600.0"
        got: "800.0"

   (compared using ==)

Ruby: Exception is not getting catched in rescue block (retry)

The exception ActiveRecord::StaleObjectError.new is not getting catch in rescue block (retry). Can you suggest why I am not able to catch Exception?

  attr_accessible :original_updated_at

  def original_updated_at
    @original_updated_at || updated_at.to_f
  end

   def set_total_and_buckets_used
    tries = 0
    begin
      if total_approved - attributes["total_amount_used"] < 0
          raise Exception.new("Total amount used is greater than approved")
      elsif self.updated_at.to_f == original_updated_at
        @original_updated_at = nil
        raise ActiveRecord::StaleObjectError.new("Car is changed while you were editing")
      else
        self.with_lock do
          attributes["updated_at"] = Time.now.utc
          Product.where(:id => self.id).update_all(attributes)
          self.attributes = attributes
        end
      end
    rescue ActiveRecord::StaleObjectError => e
      if tries < 3
        tries += 1
        retry
      else
        raise Exception.new(timeout.inspect)
      end
    end
    self.reload
    attributes
  end

Ruby: Does a locked object stay locked if an exception occurs inside it?

I am using with_lock to lock the block of instruction where I am going to call update_all. If an exception is raised inside the block, does a locked object stay locked?

For example, validator:handle_conflict raise the exception ActiveRecord::StaleObjectError, will with_lock release the lock? If it doesn't release lock, how to release the lock when exception is raised?

validate :handle_conflict, only: :update_all


  def set_total_and_buckets_used
    begin
      /////

      else
        self.with_lock do
          self.reload
          attributes["updated_at"] = Time.now.utc
          Product.where(:id => self.id).update_all(attributes)
          self.attributes = attributes
        end
      end
    rescue ActiveRecord::StaleObjectError => e
      if tries < MAX_RETRIES
        tries += 1
        sleep(1 + tries)
        retry
      else
        raise Exception.new(timeout.inspect)
      end
    end
    attributes
  end


  def handle_conflict
    if self.updated_at.to_f > original_updated_at
      @original_updated_at = nil
      raise ActiveRecord::StaleObjectError.new("Car is changed while you were editing")
    end
  end

lundi 1 octobre 2018

How to Store HTML file into Rails Model

I'm pretty much new to ROR and i'm stuck in storing html file into rails model. Can anyone help me to show how do we store HTML static file into rails model and also how to render? Thanks in advance i apologize if this question is too basic i could not find solution for this anywhere

How to redirect one page to another page in my rails app

Actually we moved /how-it-works page to https://example.com/how-its-works how can we redirect old page to new url using .htaccess file

Default value in gsub Ruby on rails

I have an array that looks like this

[
  "---\n",
  ":date: 2018-07-31\n  :story_points: 4.0\n  :remaining_hours: 4.0\n ",
  ":date: 2018-08-01\n  :story_points:    \n  :remaining_hours: 4.0\n ",
  ":date: 2018-08-22\n  :story_points: 8.0\n  :remaining_hours: 0.0\n "
]

I want the date and story_points in 2 different arrays. The output should look like below:

["2018-07-31", "2018-08-01", "2018-08-22"]

["4.0", "0.0", "8.0"]

If the value for story_points is not there then it should use default value of 0.0

I have tried till below as suggested in my earlier post by a gentlemen

arr.join.gsub(/(?<=:date: )\d{4}-\d{2}-\d{2}/).to_a

arr.join.gsub(/(?<=:story_points: )\d{1}.\d{1}/).to_a 

The above will fetch me

["2018-07-31", "2018-08-01", "2018-08-22"]

["4.0", "8.0"]

I am not able to fetch the default values. Can anyone help on this?