mercredi 26 février 2020

Does Phusion Passenger reuse processes?

If a Rails application is using class-level methods and setting class-level variables of a singleton class, and multiple requests end up sharing that same reused process, there would be data sharing issues since those requests would be sharing the same object.

I've tested this out and it seems that Phusion Passenger does indeed reuse processes and data-sharing in this particular scenario is a concern, but I can't find any info on this in Phusion Passenger's documentation.

undefined method `each' for nil:NilClass even when defined in controller

I'm getting undefined method `each' for nil:NilClass for my @store.each code when I have defined @stores in my controller. I did a basic @stores=Store.all so i'm not sure why it's nil. I have Stores populated in my db.

My controller

class PagesController < ApplicationController
  def index
    @attendances = Attendance.all
    @stores=Store.all
    @periods=Period.all
    @employees=Employee.all
    @attendances = @attendances.uniq { |p| [p.period_id, p.store_id] }
  end

  def call_action

     @attendances = Attendance.where(store_id: params[:store_id], period_id: params[:period_id]) 
     @attendances.update_all(status: "Approved")
     redirect_to root_path
  end

  def review
    @stores=Store.all
    @attendances=Attendance.where(:status =>"For Review")
    @periods=Period.all.sort_by { |obj| obj.period_end }.reverse!

  end
end

My routes

Rails.application.routes.draw do
  devise_for :users
  resources :attendances
  resources :periods
  resources :employees
  resources :stores


 get '/pages/call_action' => 'pages#call_action', :as => :call_action
 get '/pages/review' => 'pages#review', :as => :review
  # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
  root 'pages#index'
end

my view pages/review.html.erb

<% @stores.each do |store|%>
          <%= store.name %>      
<%end%>

lundi 24 février 2020

Ruby require module as shorter reference

In python you can import a module and assign a shorter reference to it, like import long_library_name as l. Is there a way to do something similar in Ruby? E.g. require 'long_library_name' as l?

mercredi 19 février 2020

mardi 18 février 2020

2 entries created by using activerecord find_or_initialize_by followed by update_attributes

I am using find_or_initialize_by followed by update_attributes to create new entry else update if entry already exists.

below is the code snippet in Ruby.

StudentResult.find_or_initialize_by(
        :course_id => course_id,
        :student_id => student_id,
        :assessment_id => assignment_id,
        ).update_attributes!(
        :total_score => assignment_total_score,
        :score => assignment_score
)

But I can see there are 2 entries for the same combination of course_id, student_id, assessment_id. This is happening rarely for some records only.

course_id, student_id, assessment_id , total_score, score, created_at , updated_at
7779,156035,29792,30,0,2020-02-06 13:54:30.325446,2020-02-06 13:54:30.325446
7779,156035,29792,30,0,2020-02-06 13:54:30.326769,2020-02-06 13:54:30.326769

Currently I do not have any unique key constraints on table StudentResult. But ideally it should create only 1 entry for course_id, student_id and assessment_id combination. I am skeptical that can this be due to some race conditions or I am missing something in my code.

Vagrant Forwarded Port - Not connecting to app - VSCode Solargraph

I just moved to Mac from Ubuntu. I figured the best way to continue development would be using Vagrant and VirtualBox as the provider. I am having issues getting solargraph to work with VSCode from within vagrant.

The VSCode Solargraph plugin gives the error: Connection to the server is erroring. Shutting down server.

My config:

VSCode config

# .vscode/settings.json
{
  "solargraph.transport": "external",
  "solargraph.externalServer": {
    "host": "localhost",
    "port": 7658
  }
}

Vagrantfile

# Vagrantfile
Vagrant.configure("2") do |config|
  config.vm.box = "bento/ubuntu-18.04"
  config.vm.network "forwarded_port", guest: 80, host: 8080
  config.vm.network "forwarded_port", guest: 7657, host: 7658
end

When I do wget localhost:7657 from within the box I get the following response suggesting the sinatra server is up and running.

vagrant@vagrant:/vagrant$ wget localhost:7657
--2020-02-18 16:58:53--  http://localhost:7657/
Resolving localhost (localhost)... ::1, 127.0.0.1
Connecting to localhost (localhost)|::1|:7657... connected.
HTTP request sent, awaiting response... 404 Not Found
2020-02-18 16:58:53 ERROR 404: Not Found.

How ever when I do wget localhost:7658 I get the following...

wget localhost:7658
--2020-02-18 22:25:44--  http://localhost:7658/
Resolving localhost (localhost)... ::1, 127.0.0.1
Connecting to localhost (localhost)|::1|:7658... failed: Connection refused.
Connecting to localhost (localhost)|127.0.0.1|:7658... connected.
HTTP request sent, awaiting response... Read error (Connection reset by peer) in headers.
Retrying.

Limitations:

  • A legacy app on Ruby 2.1
  • Installing 2.1 on MacOS through RVM or Rbenv ends with errors related to SSL and can't run it on the machine it self

Environment

  • rails 3.2.15
  • solargraph 0.10.3

Has any one encountered a similar issue and worked it out? Any advice appreciated. Thanks.

lundi 17 février 2020

How to define coffeescript method in haml file under :coffeescript tag?

I am working with ruby on rail and CoffeeScript I need to define and call a function in haml file under :coffeescript tag

I tried with following code but it generates error of undefined tabsOnLoadMethod

:coffeescript
  $ ->
    tabsOnLoadMethod ->
      alert 'hello team'

I called the method like tabsOnLoadMethod();. so where is going wrong please tell me.

error: ReferenceError: tabsOnLoadMethod is not defined

Rails Pass/Send variable from model to controller

I have some data processed from CSV file and stored in a variable. I need to send this attribute to controller on create and update a record.

Model.rb

attr_accessor :unique_messages
validate :read_csv_file

def read_csv_file
  if self.csv_file.present?
    csv_data = CSV.read(self.csv_file.path, :headers=>false)
    unique_messages = csv_data.to_h
  end
end

Controller.rb

def create
    @message_notice = MessageNotice.new(notice_attributes)

    if @message_notice.save
      flash[:success] = 'success'
    end

def notice_attributes
    attributes = params.require(:message_notice).permit(:message,:user_ids, :csv_file, :unique_messages)
end

I debugged using binding.pry and during the create/update method call before saving the params, validate :read_csv_file is executed successfully and i can see the values for variable :unique_messages on Model.rb. I need to pass that :unique_messages to controller params attribute to save in database. Now :unique_messages attribute on controller is always empty. Can any one help me how to pass the value of variable from model to controller.

Thank you.

dimanche 16 février 2020

How to scrap Amazon without 503 using Ruby?

First of all, I'm working with ruby for past 1week(only) I was trying to scrape Amazon for learning purpose

when I wrote this with Nokogiri gem code

    page = Nokogiri::HTML(open("https://www.amazon.com/"))

    puts page

this piece of code returns

.rvm/rubies/ruby-2.2.4/lib/ruby/2.2.0/open-uri.rb:358:in `open_http': 503 Service Unavailable (OpenURI::HTTPError)

In python, we can bypass it with Proxy but in ruby! I don't have an idea?, I'm finding an exception handling results which is not going to help out for getting information out of the site basically

And as we all know the site is protected, advice like buying API key is also not expected, I need some help to crack it with ruby not even with ROR, thanks in advance!

samedi 15 février 2020

How to automatically include some where conditions in rails model?

I have several models with office_id, fiscal_year_id attributes. I want these field to automatically set before querying. So, I don't have to care about data overlapping from one office to another and one fiscal year to another.

vendredi 14 février 2020

Heroku Promotion issue with and Rails/JS app and ENV variables

I have an issue very similar to this: Using runtime env with React and heroku

My JS file that retrieves the ENV variables ends up hard-coded. When I promote from Staging to Production, the staging vars remain.

My setup is:

  • Rails 3 backend
  • AngularJS frontend (we're re-platforming this year)
  • rails-environment.js.erb ( file that reads ENV[varname] and stores in JS vars

Honorable mentions: Rails Env Issue

Frequently polls happening from delayed job

Hi I am using delayed job active record gem in my production application with Postgres, a lot of background jobs are working through the delayed job

One thing I have noticed in the output of pg:outliers in our production database, the prop_exec_time is 4.5% for this query and almost 1.8 million calls happened in 45 hours.

Query:

UPDATE "delayed_jobs" SET locked_at = $1, locked_by = $2 WHERE id IN (SELECT id FROM "delayed_jobs" WHERE ((run_at <= $3 AND (locked_at IS NULL OR locked_at < $4) OR locked_by = $5) AND failed_at IS NULL) ORDER BY priority ASC, run_at ASC LIMIT $6 FOR UPDATE) RETURNING *

As per the delayed job, the polls happen every 5 seconds by default, but this happens even if there is no job to perform. Currently, there is no extra configuration in our app.

I guess I can override the default time of delayed_job, will this make any impact? Any kind of suggestion to reduce the calls

mardi 11 février 2020

Rails: Form helper how to convert this dropdown select into a radio button list

Ok....sigh. I have inherited this code (Rails 2.3.14) and I have been banging my head trying to figure out how to pull this off. I have this form_for that contains a dropdown select "g.select" that I need to be a list of checkboxes instead. How can this be done?

Here is the current code...

                <% form_for :attendance, nil, :url => {:action => "doattendance", :id => skedj.current.id}, :loading => "$(#{ loading_indicator_id("attendance_assignment_form").to_json }).show();" do |g| %>
                  <%#= g.label :attendance_type_id %>
                  <% t = Time.now.to_i%>
                  <%= g.select("attendance_type_id",
                               AttendanceType.find(:all).sort_by(&:id).collect {|p| [ p.name, p.id ] },
                               {:include_blank => true, :selected => skedj.current.attendance_type_id},
                               :id => "attendance_attendance_type_id_#{t}") %>
<!--                  TODO: convert to Radio Buttons?-->
                  <br />

               ????? <---- Radio Button code here

                  <br />

                  <%= g.submit "Save" %>
                  <%= loading_indicator_tag("attendance_assignment_form") %>
                <% end %>
              </div>

Any help appreciated

jeudi 6 février 2020

I cant execute rails server

When i run $rails s or $rails server it returns an error.

I looked for solutions but I didn't understand. I installed RVM, Ruby and Rails several times but I always get this error

I already executed the command $bundle install but it didn't work This is the error:

    25: from /Users/joel.alayon/.rvm/gems/ruby-2.6.3/gems/railties-6.0.2.1/lib/rails/application.rb:363:in `initialize!'
    24: from /Users/joel.alayon/.rvm/gems/ruby-2.6.3/gems/railties-6.0.2.1/lib/rails/initializable.rb:60:in `run_initializers'
    23: from /Users/joel.alayon/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/tsort.rb:205:in `tsort_each'
    22: from /Users/joel.alayon/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/tsort.rb:226:in `tsort_each'
    21: from /Users/joel.alayon/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/tsort.rb:347:in `each_strongly_connected_component'
    20: from /Users/joel.alayon/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/tsort.rb:347:in `call'
    19: from /Users/joel.alayon/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/tsort.rb:347:in `each'
    18: from /Users/joel.alayon/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/tsort.rb:349:in `block in each_strongly_connected_component'
    17: from /Users/joel.alayon/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/tsort.rb:431:in `each_strongly_connected_component_from'
    16: from /Users/joel.alayon/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/tsort.rb:350:in `block (2 levels) in each_strongly_connected_component'
    15: from /Users/joel.alayon/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/tsort.rb:228:in `block in tsort_each'
    14: from /Users/joel.alayon/.rvm/gems/ruby-2.6.3/gems/railties-6.0.2.1/lib/rails/initializable.rb:61:in `block in run_initializers'
    13: from /Users/joel.alayon/.rvm/gems/ruby-2.6.3/gems/railties-6.0.2.1/lib/rails/initializable.rb:32:in `run'
    12: from /Users/joel.alayon/.rvm/gems/ruby-2.6.3/gems/railties-6.0.2.1/lib/rails/initializable.rb:32:in `instance_exec'
    11: from /Users/joel.alayon/.rvm/gems/ruby-2.6.3/gems/webpacker-4.2.2/lib/webpacker/railtie.rb:84:in `block in <class:Engine>'
    10: from /Users/joel.alayon/.rvm/gems/ruby-2.6.3/gems/webpacker-4.2.2/lib/webpacker.rb:35:in `bootstrap'
     9: from /Users/joel.alayon/.rvm/gems/ruby-2.6.3/gems/webpacker-4.2.2/lib/webpacker/commands.rb:25:in `bootstrap'
     8: from /Users/joel.alayon/.rvm/gems/ruby-2.6.3/gems/webpacker-4.2.2/lib/webpacker/manifest.rb:18:in `refresh'
     7: from /Users/joel.alayon/.rvm/gems/ruby-2.6.3/gems/webpacker-4.2.2/lib/webpacker/manifest.rb:83:in `load'
     6: from /Users/joel.alayon/.rvm/gems/ruby-2.6.3/gems/webpacker-4.2.2/lib/webpacker/configuration.rb:51:in `public_manifest_path'
     5: from /Users/joel.alayon/.rvm/gems/ruby-2.6.3/gems/webpacker-4.2.2/lib/webpacker/configuration.rb:47:in `public_output_path'
     4: from /Users/joel.alayon/.rvm/gems/ruby-2.6.3/gems/webpacker-4.2.2/lib/webpacker/configuration.rb:43:in `public_path'
     3: from /Users/joel.alayon/.rvm/gems/ruby-2.6.3/gems/webpacker-4.2.2/lib/webpacker/configuration.rb:84:in `fetch'
     2: from /Users/joel.alayon/.rvm/gems/ruby-2.6.3/gems/webpacker-4.2.2/lib/webpacker/configuration.rb:88:in `data'
     1: from /Users/joel.alayon/.rvm/gems/ruby-2.6.3/gems/webpacker-4.2.2/lib/webpacker/configuration.rb:91:in `load'
/Users/joel.alayon/.rvm/gems/ruby-2.6.3/gems/webpacker-4.2.2/lib/webpacker/configuration.rb:95:in `rescue in load': Webpacker configuration file not found /Users/joel.alayon/Desktop/blog/config/webpacker.yml. Please run rails webpacker:install Error: No such file or directory @ rb_sysopen - /Users/joel.alayon/Desktop/blog/config/webpacker.yml (RuntimeError)

The error is longer, but I can't put everything, it is an example

mercredi 5 février 2020

Deploy to Engine Yard failing: 'key not found: :ciphers'

I can't deploy using the ey command:

$ ey deploy -e myapp
Loading application data from Engine Yard Cloud...
key not found: :ciphers
engineyard version 3.2.5
ruby 2.5.3p105 (2018-10-18 revision 65156) [x86_64-darwin18]

I think this has something to do with ssl. Ruby 2.5.3 was installed with rbenv and is using openssl 1.1.1 (I think I remember seeing that) though not sure how to find this after actual install...

lundi 3 février 2020

nested array ruby TypeError: no implicit conversion of Hash into Integer

def get_att(webinar_id)
  finalArray = []
    api_service = ApiService.new
    response = api_service.get_attendees(webinar_id)
    json = JSON.parse(response.body)

  for x in json['_embedded']['attendeeParticipationResponses']
    first_name = json['_embedded']['attendeeParticipationResponses'][x]['firstName']
    last_name = json['_embedded']['attendeeParticipationResponses'][x]['lastName']
    email = json['_embedded']['attendeeParticipationResponses'][x]['email']
    finalArray << [first_name, last_name, email]
  end

  # x = 2
  # first_name = json['_embedded']['attendeeParticipationResponses'][x]['firstName']
  # last_name = json['_embedded']['attendeeParticipationResponses'][x]['lastName']
  # email = json['_embedded']['attendeeParticipationResponses'][x]['email']
  # finalArray << [first_name, last_name, email]

    Rails.logger.info(finalArray)
end

This is the method (sorry the indenting is weird when pasted into stack overflow, but its normal in actual code). The idea is to return an array of arrays with all of the people and their 3 tags. I know that the JSON parse data is working because the commented out code works perfectly and I can change x assignment and it runs. The for loop also works because it counts 15 responses in json['_embedded']['attendeeParticipationResponses'] when I add a counter. So I know the 15 people are there and I can add them one by one into the final array (which I got to hold multiple arrays by the way), but for some reason the second I put it in the for loop I get the weird error which fully reads:

TypeError: no implicit conversion of Hash into Integer from /Users/josh/Documents/GitHub/schools_health/lib/go_to_webinar/to_pipeline.rb:19:in `[]'

Server Failed to Process Image

[![enter image description here][1]][1]

[1]: https://i.stack.imgur.Anyone know how to fix this error? I am using solidus to build an e-commerce websitecom/Tq6tF.png

LIKE statement but skips current post

I'm trying to use the LIKE condition to find similar posts.

Here is my code:

    @post = Post.find(params[:id])

    @post_gsub = Post.find(params[:id]).name.gsub(/something|something else|something else again/, '')

    @related_posts = Post.where("name LIKE '%#{@post_gsub}%'")

But when I pull this into the Rails view, there is currently always one match that shows up, which is the current blog post the user is on. How do I skip that current blog post so that "@related_posts" is only showing unique recommendations and not the post the user is currently on?