vendredi 24 décembre 2021

Rails tables in different languages

I'm building a multilang application, which should be support French and Flemish (there are multiple models/tables; but these two can change in the future, it needs to be dynamic)

So I want the ability to display the same "attribute" with more than a language, for example, consider a category called Cars. Lets say that it should have a color in french & flemish (amongst other characteristics).

I'm assuming the Model would stay the same, but maybe in the database it would be something like this (I don't know if it's possible)

#<Model id: 4, name: "Model 4", color:"{fr: "noir", nl:"zwart"}">

This is an example of how the its seen from the view:[1]

As you can see, the idea's not to create two Models, one in each language, for that one to contain information in both languages

Thank you

mercredi 22 décembre 2021

Run Rake task programmatically with specified environment

I'm setting up a second database with my Ruby on Rails (3) application, so I want to create a rake task to create the second development database. I'm trying to overwrite the rake db:create task such that it does all the database creation that I need. However, it seems I can't find a suitable way to perform this task. I've tried a few approaches - establishing a connection to the database from the URL:

# remove db:create from the list of rake tasks in order to override it
db_create = Rake.application.instance_variable_get('@tasks').delete('db:create')

namespace :db do
  task :create do
    if Rails.env == "development"
      # database.yml contains an entry for secondary_development, this works, as confirmed from rails console
      ActiveRecord::Base.establish_connection "postgresql://localhost/secondary_development"       
      Rake::Task["db:create"].invoke # this does nothing
    end

    # invoke original db_create task - this works
    db_create.invoke
  end
end

Another approach was to do:

# remove db:create from the list of rake tasks in order to override it
db_create = Rake.application.instance_variable_get('@tasks').delete('db:create')

namespace :db do
  task :create do
    if Rails.env == "development"
      Rails.env = "secondary_development"
      Rake::Task["db:create"].invoke
    end

    # invoke original db_create task - this doesn't work like this
    db_create.invoke
  end
end

This time only the secondary_development db:create works and the database is created as desired, but the development database is no longer created using this approach.

From one answer I found elsewhere, I thought that reenabling the task would be necessary, but that didn't change anything here and appears not to be the issue.

Finally, an approach that has worked is:

# remove db:create from the list of rake tasks in order to override it
db_create = Rake.application.instance_variable_get('@tasks').delete('db:create')

namespace :db do
  task :create do
    if Rails.env == "development"
      system("rake db:create RAILS_ENV=secondary_development")
    end

    db_create.invoke
  end
end

The only issue here is that because the rake task is being run via system, the Rails application has to load before being executed, so I'm essentially loading the application twice fully just to run the task - this will be 3 times when I add a test database into the mix.

So, the actual question(s):

Is it possible to run Rake::Task["..."] programmatically with a specified environment?

Why doesn't ActiveRecord::Base.establish_connection work in this way when creating the database? I had success when running this from Rails console.

lundi 20 décembre 2021

migrate data from one server to another while keeping few tables data unchanged basically exclude few tables while using pg_restore

Lets say my database have 4 tables A,B,C and D..Now I want while restoring data of table A and B remains unchanged and data of C and D should changed. I am using below command to restore the dump. pg_restore --verbose --no-acl --no-owner -h localhost -d db_name latest.dump command for taking dump pg_dump -Fc database_name > ~/Downloads/latest-stage.dump

here I am using clean flag because If I dont use it then It will generate error related to indexing and key constraints.

NOTE : Basically I am moving my data from one server to another server but I want data of few table should not change.

jeudi 16 décembre 2021

Printing valid parantheses with letter Ruby

Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results.

Using Variables, Input/Output, Methods, Arithmetic

```def balancedpara(result, opencount, open, close)
    
    if open < opencount
       balancedpara(result + "(", opencount, open + 1, close)
    end
    if open > close
       balancedpara(result + ")", opencount, open, close + 1)
    end
    if close == opencount
       puts "[" + result + "]"
       return
    end
end
def main()
    puts "enter parantheses"
    inp = gets.chomp
    splited = inp.split('')
    open = 0
    close = 0
    opencount = splited.count('(')
    closecount = splited.count(')')
    #result = ""
    balancedpara("", opencount, 0, 0)
end
main()```

Explanation

Here we want to take input from user with parentheses and containing letter. Remove all invalid parentheses in order to make it valid, are return all possible outputs from it.

Code explanation

Here it count total number of open parentheses and based on that it perform other operations.But that is not the right way to do. Expected output is given below.

Expected Output

"Note: The input string may contain letters other than the parentheses ( and ). Example 1:

Input: ""()())()"" Output: [""()()()"", ""(())()""]

Example 2:

Input: ""(a)())()"" Output: [""(a)()()"", ""(a())()""]

Example 3:

Input: "")("" Output: [""""]"

dimanche 12 décembre 2021

Ruby on Rails 2.3 LTS upgrade issue - undefined method `search' for ["http://rubygems.org/"]:Array (NoMethodError)

I am upgrading Rails 2.3 LTS Free Community Edition of Makandra Rails 2.3 Long Term Support to Rails 6. With a lot of difficulty I was able to bundle install gems required. But I am not able to boot up to rails console. Without it running I won't be able to use the rails:update / upgrade scripts to upgrade...

Bundler version 1.17.3

Here is the error stack:

[adminuser@localhost usabmx]$ bundle exec script/console
Loading development environment (Rails 2.3.18)
/home/adminuser/Documents/freelance_projects/bmx_repo/usabmx/config/environment.rb:26: warning: already initialized constant Gem::SourceIndex
/home/adminuser/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/gems/bundler-1.17.3/lib/bundler/rubygems_integration.rb:417: warning: previous definition of SourceIndex was here
/home/adminuser/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/bundler/gems/rails-c2be41e8dba7/railties/lib/rails/gem_dependency.rb:104:in `specification': undefined method `search' for ["http://rubygems.org/"]:Array (NoMethodError)
    from /home/adminuser/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/bundler/gems/rails-c2be41e8dba7/railties/lib/rails/plugin/locator.rb:81:in `block in plugins'
    from /home/adminuser/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/bundler/gems/rails-c2be41e8dba7/railties/lib/rails/plugin/locator.rb:81:in `each'
    from /home/adminuser/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/bundler/gems/rails-c2be41e8dba7/railties/lib/rails/plugin/locator.rb:81:in `inject'
    from /home/adminuser/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/bundler/gems/rails-c2be41e8dba7/railties/lib/rails/plugin/locator.rb:81:in `plugins'
    from /home/adminuser/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/bundler/gems/rails-c2be41e8dba7/railties/lib/rails/plugin/loader.rb:109:in `block in locate_plugins'
    from /home/adminuser/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/bundler/gems/rails-c2be41e8dba7/railties/lib/rails/plugin/loader.rb:108:in `map'
    from /home/adminuser/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/bundler/gems/rails-c2be41e8dba7/railties/lib/rails/plugin/loader.rb:108:in `locate_plugins'
    from /home/adminuser/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/bundler/gems/rails-c2be41e8dba7/railties/lib/rails/plugin/loader.rb:32:in `all_plugins'
    from /home/adminuser/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/bundler/gems/rails-c2be41e8dba7/railties/lib/rails/plugin/loader.rb:22:in `plugins'
    from /home/adminuser/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/bundler/gems/rails-c2be41e8dba7/railties/lib/rails/plugin/loader.rb:53:in `add_plugin_load_paths'
    from /home/adminuser/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/bundler/gems/rails-c2be41e8dba7/railties/lib/initializer.rb:310:in `add_plugin_load_paths'
    from /home/adminuser/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/bundler/gems/rails-c2be41e8dba7/railties/lib/initializer.rb:139:in `process'
    from /home/adminuser/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/bundler/gems/rails-c2be41e8dba7/railties/lib/initializer.rb:113:in `run'
    from /home/adminuser/Documents/freelance_projects/bmx_repo/usabmx/config/environment.rb:40:in `<top (required)>'
    from /home/adminuser/.rbenv/versions/2.1.5/lib/ruby/2.1.0/irb/init.rb:286:in `require'
    from /home/adminuser/.rbenv/versions/2.1.5/lib/ruby/2.1.0/irb/init.rb:286:in `block in load_modules'
    from /home/adminuser/.rbenv/versions/2.1.5/lib/ruby/2.1.0/irb/init.rb:284:in `each'
    from /home/adminuser/.rbenv/versions/2.1.5/lib/ruby/2.1.0/irb/init.rb:284:in `load_modules'
    from /home/adminuser/.rbenv/versions/2.1.5/lib/ruby/2.1.0/irb/init.rb:20:in `setup'
    from /home/adminuser/.rbenv/versions/2.1.5/lib/ruby/2.1.0/irb.rb:380:in `start'
    from /home/adminuser/.rbenv/versions/2.1.5/bin/irb:11:in <main>

Here is the gem env output:

[adminuser@localhost usabmx]$ gem env
RubyGems Environment:
  - RUBYGEMS VERSION: 1.8.30
  - RUBY VERSION: 2.1.5 (2014-11-13 patchlevel 273) [x86_64-linux]
  - INSTALLATION DIRECTORY: /home/adminuser/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0
  - RUBY EXECUTABLE: /home/adminuser/.rbenv/versions/2.1.5/bin/ruby
  - EXECUTABLE DIRECTORY: /home/adminuser/.rbenv/versions/2.1.5/bin
  - RUBYGEMS PLATFORMS:
    - ruby
    - x86_64-linux
  - GEM PATHS:
     - /home/adminuser/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0
     - /home/adminuser/.gem/ruby/2.1.0
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :benchmark => false
     - :backtrace => false
     - :bulk_threshold => 1000
     - "gem" => "--no-rdoc --no-ri"
  - REMOTE SOURCES:
     - http://rubygems.org/

Here is the Gemfile:

source "https://rubygems.org"

gem 'countries'
gem 'nokogiri'
gem 'iconv'

# This is Rails 2.3 LTS - http://makandracards.com/railslts/16137-installing-rails-lts
gem 'rails', :git => 'https://github.com/makandra/rails.git', :branch => '2-3-lts'
gem 'rack'
#gem 'rdoc'
gem 'rake'

gem 'pg'
gem 'stripe'

# Quickbooks/Authnet export gems
gem 'authorizenet' # This is for transaction batch API
# In the future, need to switch back to the standard repository if they accept
# our pull request for Rails 2.3
gem 'riif', :git => "https://github.com/newmedio/riif.git"

# This is for the Satori Address Validation API
# gem 'savon', '~> 2.0'
# gem 'savon', github: 'savonrb/savon' # This fails when running bundle install

gem 'spreadsheet'

gem 'will_paginate', '= 2.3.16'

gem 'byebug'

gem 'aws-s3'
gem 'ruby-aaws'
gem 'mini_magick', '= 1.2.3'
gem 'rvideo'

gem 'geokit', '= 1.13.0'
gem 'prawn', '= 1.0.0.rc1'
gem 'combine_pdf'
gem 'zip-codes'

gem 'barby'
gem 'chunky_png'
gem 'httparty'
gem 'json'
gem 'json_cve_2020_10663'
gem 'twitter'
gem 'icalendar'

gem 'ruby-debug-ide', :group => "development"
gem 'debase', :group => "development"
gem 'capistrano', '= 3.3.3', :group => "development"
gem 'capistrano-bundler', :group => "development"
gem 'capistrano-passenger', :group => "development"
gem 'capistrano-rails', :group => "development"
gem 'capistrano-rvm', :group => "development"

gem 'linode'

gem 'recaptcha', '= 0.4.0', :require => "recaptcha/rails"
gem 'honeypot-captcha'

samedi 11 décembre 2021

Merging and grouping hashes value based on keys

I have an array of hashes (in this example 2 hashes, but there could be much more):

array = [
  { "answers"=>{
      "42"=>"61",
      "43"=>["0", "64", "0", "0", "66", "0"],
      "44"=>"It has always been pretty bad. None of the questions were answered properly.",
      "45"=>["0", "68", "0", "69", "0"]
    }
  },
  { "answers"=>{
      "42"=>"61”,
      "43"=>["0", "64", "0", "0", "66", "0", "67"],
      "44"=>"They are all amazing",
      "45"=>["0", "68", "0", "69", "0"]
    }
  }
] 

I would like to be able to merge the two hashes, group them by keys, and count the value per duplicated key.

The result would be something like :

{ "42" => ["61", 2],
  "43" => [
            [["64", "66"], 1],
            [["64", "66", "67"],1]
          ],
  "44" => [
            ["It has always been pretty bad. None of the questions were answered properly.",1],
            ["They are all amazing",1]
          ],
  "45" => [
            [["68", "69"],2]
          ]
}

Also note that:

  1. Certain values are arrays, of which the "0" have been removed during the process.
  2. The number following each array is the count of occurence.

Does anyone knows how to do this please? This is as far as I could get with the original data (active records)

vendredi 10 décembre 2021

How to add confirm addeventlistener to different view pages in rails

I have two different views: edit.html.erb and create.html.erb I want to add similar functionality onclick a checkbox on both the pages but want to avoid writing redundant code in both the files:

Currently what I am doing in both the files: In create.html.erb

<script>
    function onclick (event) {
        var message = 'Are you sure ?';
        confirm(message) || event.preventDefault();
        }
    var elem = document.getElementById('create');
    elem.addEventListener('click', onclick);
</script>

In edit.html.erb

<script>
    function onclick (event) {
        var message = 'Are you sure ?';
        confirm(message) || event.preventDefault();
        }
    var elem = document.getElementById('edit');
    elem.addEventListener('click', onclick);
</script>

Ideally I want to have a js file where both these events can be captured when clicking on either create or edit instead of writing this method individually on both files. What is a good way to do DRY here.

jeudi 9 décembre 2021

Ruby loop through and print out available methods/attributes

How can I list out all the attributes or methods available for the provider below?

Other scripts make use of providers method/attribute like below:

if provider
  provider.miq_templates.each do |template|
  ....

if provider
  provider.security_groups.each do |security_group|
  ....

So I want to print out everything it has like miq_templates, security_groups etc.,

I tried the following but it only prints provider is : AWS. How can I print everything it has?

if provider
  log(:info, "provider is : #{provider}")
end

Here is the code

def get_provider(provider_id=nil)
  $evm.root.attributes.detect { |k,v| provider_id = v if k.end_with?('provider_id') } rescue nil
  provider = $evm.vmdb(:ManageIQ_Providers_Amazon_CloudManager).find_by_id(provider_id)
  log(:info, "Found provider: #{provider.name} via provider_id: #{provider.id}") if provider

  if !provider
    provider = $evm.vmdb(:ManageIQ_Providers_Amazon_CloudManager).first
    if provider
      log(:info, "Found provider: #{provider.name} via default method")
    else
      bail_out('< No providers found, check RBAC tags >')
    end
  end
  provider ? (return provider) : (return nil)
end


provider = get_provider(query_catalogitem(:src_ems_id)) || get_provider_from_template()


if provider
  log(:info, "provider is : #{provider}")
end

if provider
  provider.miq_templates.each do |template|
    log(:info, "miq_templates is : #{template.id}")
    next if template.archived || template.orphaned  
    #dialog_hash[template.guid] = "#{template.name} on #{provider.name}"
    dialog_hash[template.id] = "#{template.name} on #{provider.name}"
  end
else
  # no provider so list everything
  $evm.vmdb(:ManageIQ_Providers_Amazon_CloudManager_Template).all.each do |template|
    next if template.archived || template.orphaned
     #dialog_hash[template[:guid]] = "#{template.name} on #{template.ext_management_system.name}"
      dialog_hash[template[:id]] = "#{template.name} on #{template.ext_management_system.name}"
  end
end

mercredi 8 décembre 2021

How should I write the query for ElasticSearch in Rails?

I have to write a query in my SortBuilder.rb in which I want the count of occurrence of a word (that is coming in this method in the variable value) in the results and sort the results according to the word count.

I also want to display the count later so I want to store them in a variable.

My current logic is --

   sort: [
     query: value,
     aggs:  {
       my_terms: {
         filters: {
           value: { term: { "title" => "#{value}" }}
         }
       }
     }
   ]

Ruby - NoMethodError: undefined method for hash

How can I get the value of attribute and set it in a varaible?

Here is an example: The log shows all attributes. I want to fetch dialog_param_placement_availability_zone value and assign it to a variable.

$evm.root.attributes.sort.each { |k, v| log(:info, "\t Attribute: #{k} = #{v}")}


[----] I, [2021-12-08T07:42:45.138328 #318:2b28283f1fa8]  INFO -- automation: <AEMethod list_ec2_cloudsubnets_ids>      Attribute: data_type = string
[----] I, [2021-12-08T07:42:45.139071 #318:2b28283f1fa8]  INFO -- automation: <AEMethod list_ec2_cloudsubnets_ids>      Attribute: dialog_guest_access_key_pair = 5
[----] I, [2021-12-08T07:42:45.139928 #318:2b28283f1fa8]  INFO -- automation: <AEMethod list_ec2_cloudsubnets_ids>      Attribute: dialog_instance_type = 26
[----] I, [2021-12-08T07:42:45.140745 #318:2b28283f1fa8]  INFO -- automation: <AEMethod list_ec2_cloudsubnets_ids>      Attribute: dialog_list_ec2_cloudsubnets_ids =
[----] I, [2021-12-08T07:42:45.141400 #318:2b28283f1fa8]  INFO -- automation: <AEMethod list_ec2_cloudsubnets_ids>      Attribute: dialog_list_ec2_template_guids = 60b75115-4f29-49fd-a8d5-d27364cfbef5
[----] I, [2021-12-08T07:42:45.142041 #318:2b28283f1fa8]  INFO -- automation: <AEMethod list_ec2_cloudsubnets_ids>      Attribute: dialog_number_of_vms =
[----] I, [2021-12-08T07:42:45.142670 #318:2b28283f1fa8]  INFO -- automation: <AEMethod list_ec2_cloudsubnets_ids>      Attribute: dialog_param_placement_availability_zone = 1
[----] I, [2021-12-08T07:42:45.143333 #318:2b28283f1fa8]  INFO -- automation: <AEMethod list_ec2_cloudsubnets_ids>      Attribute: dialog_vm_name =
[----] I, [2021-12-08T07:42:45.144040 #318:2b28283f1fa8]  INFO -- automation: <AEMethod list_ec2_cloudsubnets_ids>      Attribute: enable_rbac = false
[----] I, [2021-12-08T07:42:45.144976 #318:2b28283f1fa8]  INFO -- automation: <AEMethod list_ec2_cloudsubnets_ids>      Attribute: miq_group = #<MiqAeMethodService::MiqAeServiceMiqGroup:0x0000565050716dc0>
[----] I, [2021-12-08T07:42:45.145857 #318:2b28283f1fa8]  INFO -- automation: <AEMethod list_ec2_cloudsubnets_ids>      Attribute: miq_server = #<MiqAeMethodService::MiqAeServiceMiqServer:0x000056504ffed328>
[----] I, [2021-12-08T07:42:45.146521 #318:2b28283f1fa8]  INFO -- automation: <AEMethod list_ec2_cloudsubnets_ids>      Attribute: miq_server_id = 1
[----] I, [2021-12-08T07:42:45.147148 #318:2b28283f1fa8]  INFO -- automation: <AEMethod list_ec2_cloudsubnets_ids>      Attribute: object_name = list_ec2_cloudsubnets_ids
[----] I, [2021-12-08T07:42:45.147792 #318:2b28283f1fa8]  INFO -- automation: <AEMethod list_ec2_cloudsubnets_ids>      Attribute: required = true
[----] I, [2021-12-08T07:42:45.148829 #318:2b28283f1fa8]  INFO -- automation: <AEMethod list_ec2_cloudsubnets_ids>      Attribute: service_template = #<MiqAeMethodService::MiqAeServiceServiceTemplate:0x000056504beeddf0>
[----] I, [2021-12-08T07:42:45.149803 #318:2b28283f1fa8]  INFO -- automation: <AEMethod list_ec2_cloudsubnets_ids>      Attribute: service_template_id = 6
[----] I, [2021-12-08T07:42:45.150583 #318:2b28283f1fa8]  INFO -- automation: <AEMethod list_ec2_cloudsubnets_ids>      Attribute: sort_by = description
[----] I, [2021-12-08T07:42:45.151554 #318:2b28283f1fa8]  INFO -- automation: <AEMethod list_ec2_cloudsubnets_ids>      Attribute: sort_order = ascending
[----] I, [2021-12-08T07:42:45.153210 #318:2b28283f1fa8]  INFO -- automation: <AEMethod list_ec2_cloudsubnets_ids>      Attribute: tenant = #<MiqAeMethodService::MiqAeServiceTenant:0x000056504e1d0160>
[----] I, [2021-12-08T07:42:45.154263 #318:2b28283f1fa8]  INFO -- automation: <AEMethod list_ec2_cloudsubnets_ids>      Attribute: user = #<MiqAeMethodService::MiqAeServiceUser:0x000056504e1d1470>
[----] I, [2021-12-08T07:42:45.154917 #318:2b28283f1fa8]  INFO -- automation: <AEMethod list_ec2_cloudsubnets_ids>      Attribute: user_id = 1
[----] I, [2021-12-08T07:42:45.155546 #318:2b28283f1fa8]  INFO -- automation: <AEMethod list_ec2_cloudsubnets_ids>      Attribute: vmdb_object_type = service_template

I tried the following

availability_zone_id = $evm.root.attributes.dialog_param_placement_availability_zone`

But I get the error

undefined method dialog_param_placement_availability_zone' for #<Hash:0x00005650509e5808> (NoMethodError)`

vendredi 3 décembre 2021

How to convert two strings into an array of two in Ruby

I am looking to extract keys and values from a hash. I manage to retrieve the data but in the wrong format. I am doing the following:

@message_count_series = @messages.collect { |p| "[#{p["created_at"]}, #{p["total_cnt"]}]" }
 => ["[2021-12-02 13:21:19.837233, 3]", "[2021-11-20 13:54:54.846048, 3]"] 

What I would like to obtain is:

 => [[2021-12-02 13:21:19.837233, 3], [2021-11-20 13:54:54.846048, 3]] 

Just without the quote (not a string).

I tried the following :

@message_opened_series = @messages.collect { |p| ["#{p["created_at"]}, #{p["opened_cnt"]}"] }
 => [["2021-12-02 13:21:19.837233, 1"], ["2021-11-20 13:54:54.846048, 0"]] 

Which takes me closer, but now my data are considered a string inside the array.

The following appear to work, but might not be very robust

@message_opened_series = @messages.collect { |p| [DateTime.parse("#{p["created_at"]}"), ("#{p["opened_cnt"]}").to_i] }
 => [[Thu, 02 Dec 2021 13:21:19 +0000, 1], [Sat, 20 Nov 2021 13:54:54 +0000, 0]] 

Is there a better way to do this please ?

jeudi 2 décembre 2021

Generating UUIDs with 6 character

For ruby, Gem UUID generate 36-character UUIDs.
I want to generate only 6-character. It is possible?
Is it possible to add a id to increase uniqueness?

mercredi 1 décembre 2021

how to format the search query to remove special characters while searching mobile number, REGEXP_REPLACE

As my table was contacts which contains data in us format as(###)-###-#### and there were input field in which user enters the normal string format of ######

this was my current query

contacts.where("REGEXP_REPLACE(contacts.phone_number,'[^0-9A-Za-z]','','g') ilike :search", {search: "%#{mob_num}%"})

so as it doesn't fetch any data, while giving the correct input also, what was wrong in my query, as i try to modify the data in normal format for searching the phone number in table...

please provide a solution for it

thanks in advance

ruby I want to know the overlapping value by comparing the two excels

enter image description here

require 'roo'

require 'rainbow'

roo = Roo::Spreadsheet.open('./cause/jjjjob.xlsx') # excel 1

roo1 = Roo::Spreadsheet.open('./cause/jjjjob_2.xlsx') # excel 2

for i in 2..roo.column(2).length

for j in 2..roo1.column(1).length
    excel_2_peple = roo1.column(1)
    ss = roo.row(i)
    bb = roo1.row(j)
    ss.each_slice(2) do |name, job|
        if name == excel_2_peple
            puts Rainbow("same name = #{name}, excel_1 peple job #{job}  excel_2 peple job #{????}").green
        end
    end
end

end

Why all values of a nested hash are updated when merging another hash?

I have following hash:

hash = {2021=>{:gastosCompra=>0}, 2022=>{:gastosCompra=>0}, 2023=>{:gastosCompra=>0}}

I am trying to update gastosCompra of key year 2021. I've tried merge, deep_merge, but unfortunately all the other keys are updated too:

hash[year][:gastosCompra] = 555
hash[year].merge!({gastosCompra: 555})
hash[year].deep_merge!({gastosCompra: 555})

This is the result:

hash = {2021=>{:gastosCompra=>555}, 2022=>{:gastosCompra=>555}, 2023=>{:gastosCompra=>555}}

Why all the nested hashes are updated if I just want to update year 2021? I guess I could loop over the keys and stop when I find the year 2021, but I want to avoid that.

how to remove special characters while fetching the data from the table

i have a table that holds phone numbers in the format of (###)-###-#### and have one seach bar to search the phone numbers,as the data were stored in us format(###)_###-####

and users will enter in ##### format so how to perform search querey that neglects the special characters('(',')','-') while fetching the data from table

my current query is contact = contact.where('contact.phone_number ilike :search', {search: "%#{input_number}%"} )

where input number holds the user entered input ex("123456789")

thanks in advance

How to format the search input to us format phone number

as in table the phone numbers are stored in us format as (###)-###-####

and i tried to search it, as im getting the input from user as string(phone number)

and i tried to convert that as

 search_input = search_input.unpack('A3A3A4').join('-').insert(0,'(').insert(4,')')

it works if the complete phone number is typed, but

as if the user input single digit , the query searches like %#--% like this and nothing

gets fetched , so how to modify that command

my query will look like

    result = users.where('users.phone_number_1 ilike :search', {search: "%#{search_input}%"})

or on the above query is there any posiblity to remove the special charcter('(',')','-') while searching?, so that it searches with the phone number alone..

thanks in advance

lundi 29 novembre 2021

How to use ilike for phone number filter

Hi im fetching the user input and displaying the records that matches the condition, my query will look like

customers = customers.where('customers.contact_num ilike :search', {search: "%#{options[:search_contact]}%"})

here in db the contact number is stored in string with the format (091)-234-5678 like that

on while searching the user on basis of contact number if i search like this

091 it filters the number correctly, but while searching like 0912, it doesn't display record due to the braces, so how to modify the query to neglect the ) and - while searching.. As im new to the domain please help me out

thanks in advance

Custom query to fetch all entries of a table and that only contains first of many duplicates based on a specific column

I have a Location model and the table looks like

   id |      name      | vin |     ip_address    |         created_at         |         updated_at    ----+----------------+------+---------------+----------------------------+------------------------
    0 | default |    0 | 0.0.0.0/0          | 2021-11-08 11:54:26.822623 | 2021-11-08 11:54:26.822623
    1 | admin  |    1 | 10.108.150.143    | 2021-11-08 11:54:26.82885  | 2021-11-08 11:54:26.82885
    2 | V122  |    122| 10.108.150.122    | 2021-11-08 11:54:26.82885  | 2021-11-08 11:54:26.82885  
    3 | V123 |    123| 10.108.150.123   | 2021-11-08 11:54:26.82885  | 2021-11-08 11:54:26.82885
    4 | V124  |    124| 10.108.150.124   | 2021-11-08 11:54:26.82885  | 2021-11-08 11:54:26.82885
    5 | V122  |    122| 10.108.150.122    | 2021-11-08 11:54:26.82885  | 2021-11-08 11:54:26.82885
    6 | V125  |    122| 10.108.150.125   | 2021-11-08 11:54:26.82885  | 2021-11-08 11:54:26.82885

My method in the Location model

   def self.find_all_non_duplicate
     return self.find(:all, :conditions => "id <> 1")
   end

I want to fetch all entries of the locations table except the entry with id = 1 and that contains only the first entry of many duplicates based on the column ip_address.

Since ip_address of id = 2 and id = 5 is duplicate. I want to keep the first entry of many duplicates i.e., id = 2.

The expected result is

 id |      name      | vin |     ip_address    |         created_at         |         updated_at           ----+----------------+------+---------------+----------------------------+------------------------
 0 | default |    0 | 0.0.0.0/0          | 2021-11-08 11:54:26.822623 | 2021-11-08 11:54:26.822623
 2 | V122  |    122| 10.108.150.122    | 2021-11-08 11:54:26.82885  | 2021-11-08 11:54:26.82885
 3 | V123 |    123| 10.108.150.123   | 2021-11-08 11:54:26.82885  | 2021-11-08 11:54:26.82885
 4 | V124  |    124| 10.108.150.124   | 2021-11-08 11:54:26.82885  | 2021-11-08 11:54:26.82885
 6 | V125  |    122| 10.108.150.125   | 2021-11-08 11:54:26.82885  | 2021-11-08 11:54:26.82885

The entries with id's 1 and 5 to be ignored

dimanche 28 novembre 2021

Unable to remove action_mailbox

I'm using Ruby 3.0.3 + Rails 6.1.4. I tried to remove action_mailbox (and any unused railties) and have the following in my application.rb

%w(
  action_controller/railtie
  action_view/railtie
  active_job/railtie
  sprockets/railtie
).each do |railtie|
  begin
    require railtie
  rescue LoadError
  end
end

I also commented out any action_mailbox related configs.

Here's the Gemfile

# gem 'rails', '~> 6.1', '>= 6.1.4' # note this is commented out. I know it's overkill, but this didn't work
gem 'actionpack', '~> 6.1', '>= 6.1.4'
gem 'actionview', '~> 6.1', '>= 6.1.4'
gem 'activesupport', '~> 6.1', '>= 6.1.4'
gem 'railties', '~> 6.1', '>= 6.1.4'
gem 'sprockets-rails', '~> 3.4', '>= 3.4.1'

However, when I run bundle exec derailed bundle:mem, I still see action_mailbox

  rails/all: 62.25 MiB
    action_mailbox/engine: 33.3594 MiB
      action_mailbox: 33.3281 MiB
        action_mailbox/mail_ext: 33.2969 MiB
          action_mailbox/mail_ext/address_equality.rb: 31.9375 MiB
            mail/elements/address: 31.9375 MiB
              mail/parsers/address_lists_parser: 31.9063 MiB (Also required by: mail/parsers)
                mail/parsers: 1.7656 MiB
                  mail/parsers/received_parser: 1.1875 MiB

I don't think any Gems are depending on it, but is there a way that I can find out?

I tried running bundle exec gem dependency -R but I'm not sure if it's very helpful:

Gem actionmailbox-6.1.4
  actionpack (= 6.1.4)
  activejob (= 6.1.4)
  activerecord (= 6.1.4)
  activestorage (= 6.1.4)
  activesupport (= 6.1.4)
  mail (>= 2.7.1)
  Used by
    rails-6.1.4 (actionmailbox (= 6.1.4))

Gem rails-6.1.4
  actioncable (= 6.1.4)
  actionmailbox (= 6.1.4)
  actionmailer (= 6.1.4)
  actionpack (= 6.1.4)
  actiontext (= 6.1.4)
  actionview (= 6.1.4)
  activejob (= 6.1.4)
  activemodel (= 6.1.4)
  activerecord (= 6.1.4)
  activestorage (= 6.1.4)
  activesupport (= 6.1.4)
  bundler (>= 1.15.0)
  railties (= 6.1.4)
  sprockets-rails (>= 2.0.0)

samedi 27 novembre 2021

Having trouble running rails commands

Errors

/full-stack-review/cheese-shop/vendor/cache/ruby/2.6.0/gems/railties-6.1.4.1/lib/rails/commands/rake/rake_command.rb:19:in `block in perform'
/full-stack-review/cheese-shop/vendor/cache/ruby/2.6.0/gems/railties-6.1.4.1/lib/rails/commands/rake/rake_command.rb:18:in `perform'
/full-stack-review/cheese-shop/vendor/cache/ruby/2.6.0/gems/railties-6.1.4.1/lib/rails/command.rb:50:in `invoke'
/full-stack-review/cheese-shop/vendor/cache/ruby/2.6.0/gems/railties-6.1.4.1/lib/rails/commands.rb:18:in `<main>'
/full-stack-review/cheese-shop/vendor/cache/ruby/2.6.0/gems/bootsnap-1.9.3/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `require'
/full-stack-review/cheese-shop/vendor/cache/ruby/2.6.0/gems/bootsnap-1.9.3/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `block in require_with_bootsnap_lfi'
/full-stack-review/cheese-shop/vendor/cache/ruby/2.6.0/gems/bootsnap-1.9.3/lib/bootsnap/load_path_cache/loaded_features_index.rb:100:in `register'
/full-stack-review/cheese-shop/vendor/cache/ruby/2.6.0/gems/bootsnap-1.9.3/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require_with_bootsnap_lfi'
/full-stack-review/cheese-shop/vendor/cache/ruby/2.6.0/gems/bootsnap-1.9.3/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:31:in `require'
/full-stack-review/cheese-shop/bin/rails:5:in `<top (required)>'
/full-stack-review/cheese-shop/vendor/cache/ruby/2.6.0/gems/spring-3.1.1/lib/spring/client/rails.rb:30:in `load'
/full-stack-review/cheese-shop/vendor/cache/ruby/2.6.0/gems/spring-3.1.1/lib/spring/client/rails.rb:30:in `call'
/full-stack-review/cheese-shop/vendor/cache/ruby/2.6.0/gems/spring-3.1.1/lib/spring/client/command.rb:7:in `call'
/full-stack-review/cheese-shop/vendor/cache/ruby/2.6.0/gems/spring-3.1.1/lib/spring/client.rb:30:in `run'
/full-stack-review/cheese-shop/vendor/cache/ruby/2.6.0/gems/spring-3.1.1/bin/spring:49:in `<top (required)>'
/full-stack-review/cheese-shop/vendor/cache/ruby/2.6.0/gems/spring-3.1.1/lib/spring/binstub.rb:11:in `load'
/full-stack-review/cheese-shop/vendor/cache/ruby/2.6.0/gems/spring-3.1.1/lib/spring/binstub.rb:11:in `<top (required)>'
/full-stack-review/cheese-shop/bin/spring:10:in `block in <top (required)>'
/full-stack-review/cheese-shop/bin/spring:7:in `tap'
/full-stack-review/cheese-shop/bin/spring:7:in `<top (required)>'

Steps I tried

  • Updating ruby gems
  • Spring stop
  • Uninstall Ruby on Mac w/ rvm

I am not sure at which point this error started to persist. Tried my best to restore this codebase.

vendredi 26 novembre 2021

To upgrade Rails 5.1 migrations to Rails 6.0, I can't exchange add_attachment to what

I am upgrading ruby version from 2.5.7 to 3.0.0 So I upgrade rails version from 5.1 to 6.1 also.

After version upgrade, I tried to migrate database. Then I am facing following issues: [screenshot][1]

Here is the migrations file source:

class AddAttachmentAvatarToUsers < ActiveRecord::Migration[5.1]
  def self.up
    change_table :users do |t|
    t.attachment :avatar
  end
end

  def self.down
    remove_attachment :users, :avatar
  end
end

I am using gem 'paperclip', '~> 5.0.0'

after googling I tried with this codes.

class AddAttachmentAvatarToUsers < ActiveRecord::Migration[6.1]
  def self.up
    add_attachment :users, :avatar
  end

  def self.down
    remove_attachment :users, :avatar
  end
end

Then it causing bellow issues

[screenshot2][2]

Pls help me fix this issue. [1]: https://i.stack.imgur.com/SFNmK.png [2]: https://i.stack.imgur.com/fMHYY.png

How to include a if condition inside where clause in rails

I have the following method:

def add_books(year, industry, author_id=nil)
  Books.where(publication_year:year, author: author_id)
end

How can I update the query to not filter by author_id if it is not passed?

Rspec reloads removes the value that updated earlier

why reload removes the values that has been updated on before(:each)

is there any other approach for doing such things

thanks in advance i have written my rspec as below

let!(:book){FactoryGirl.create(:book)
let!(:book2){FactoryGirl.create(:book)

before(:each) do
  book.update_column(name:"my new book")
  book2.update_column(name:"my second book")
end

it "does updation of name" do
  data = book.rename_book
  expect(book.reload.name).to eq("some new name")
  expect(book2.reload.name).to not_eq("some new name") // here it removes the book name and make it as nil, how to prevent this
end

//the book2.reload is removes the book name and update it as nil, as how to fix it as it should display the second book name, instead it displays nil for that book.

mardi 23 novembre 2021

While running the rspec it shows does not implement( allow_any_instance_of )

My rspec line

allow_any_instance_of(School).to receive(:admission).and_return(:body)

I have my admission method in my lib/school.rb module School

def self.admission()

like this, but when i run the rspec it throws error like

Failure/Error: allow_any_instance_of(School).to receive(:admission),and_return(:body)
       School does not implement #admission

lundi 22 novembre 2021

Specified 'postgresql' for database adapter, but the gem is not loaded. Add `gem 'pg'` to your Gemfile

Error setting up my database when trying to clone this repo (https://github.com/ssaffa38/prelaunchr) and running it on my local server. Where I'm getting is stuck is where it is asking to setup local database.

The code I'm putting in is:

bundle exec rake db:create
bundle exec rake db:migrate

The error I keep getting is:

Specified 'postgresql' for database adapter, but the gem is not loaded. Add gem 'pg' to your Gemfile (and ensure its version is at the minimum required by ActiveRecord).

What I've tried to do is update my Gemfile, but still have no luck.

Here is the full error report in my terminal (not sure if this is where I have to post this...):

Specified 'postgresql' for database adapter, but the gem is not loaded. Add gem 'pg' to your Gemfile (and ensure its version is at the minimum required by ActiveRecord). /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/connection_adapters/connection_specification.rb:177:in rescue in spec' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/connection_adapters/connection_specification.rb:174:in spec' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/connection_handling.rb:50:in establish_connection' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/tasks/postgresql_database_tasks.rb:6:in establish_connection' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/tasks/postgresql_database_tasks.rb:76:in establish_master_connection' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/tasks/postgresql_database_tasks.rb:14:in create' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/tasks/database_tasks.rb:93:in create' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/tasks/database_tasks.rb:107:in block in create_current' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/tasks/database_tasks.rb:278:in block in each_current_configuration' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/tasks/database_tasks.rb:277:in each' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/tasks/database_tasks.rb:277:in each_current_configuration' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/tasks/database_tasks.rb:106:in create_current' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/railties/databases.rake:17:in block (2 levels) in <top (required)>' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/task.rb:281:in block in execute' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/task.rb:281:in each' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/task.rb:281:in execute' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/task.rb:219:in block in invoke_with_call_chain' /Users/sahrsaffa/.rvm/rubies/ruby-2.5.3/lib/ruby/2.5.0/monitor.rb:226:in mon_synchronize' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/task.rb:199:in invoke_with_call_chain' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/task.rb:188:in invoke' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/application.rb:160:in invoke_task' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/application.rb:116:in block (2 levels) in top_level' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/application.rb:116:in each' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/application.rb:116:in block in top_level' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/application.rb:125:in run_with_threads' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/application.rb:110:in top_level' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/application.rb:83:in block in run' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/application.rb:186:in standard_exception_handling' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/application.rb:80:in run' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/exe/rake:27:in <top (required)>' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/bin/rake:23:in load' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/bin/rake:23:in ' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/bin/ruby_executable_hooks:22:in eval' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/bin/ruby_executable_hooks:22:in ' Couldn't create database for {"adapter"=>"postgresql", "database"=>"prelaunchr_development", "host"=>"localhost"} Specified 'postgresql' for database adapter, but the gem is not loaded. Add gem 'pg' to your Gemfile (and ensure its version is at the minimum required by ActiveRecord). /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/connection_adapters/connection_specification.rb:177:in rescue in spec' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/connection_adapters/connection_specification.rb:174:in spec' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/connection_handling.rb:50:in establish_connection' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/tasks/postgresql_database_tasks.rb:6:in establish_connection' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/tasks/postgresql_database_tasks.rb:76:in establish_master_connection' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/tasks/postgresql_database_tasks.rb:14:in create' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/tasks/database_tasks.rb:93:in create' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/tasks/database_tasks.rb:107:in block in create_current' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/tasks/database_tasks.rb:278:in block in each_current_configuration' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/tasks/database_tasks.rb:277:in each' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/tasks/database_tasks.rb:277:in each_current_configuration' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/tasks/database_tasks.rb:106:in create_current' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/railties/databases.rake:17:in block (2 levels) in <top (required)>' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/task.rb:281:in block in execute' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/task.rb:281:in each' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/task.rb:281:in execute' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/task.rb:219:in block in invoke_with_call_chain' /Users/sahrsaffa/.rvm/rubies/ruby-2.5.3/lib/ruby/2.5.0/monitor.rb:226:in mon_synchronize' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/task.rb:199:in invoke_with_call_chain' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/task.rb:188:in invoke' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/application.rb:160:in invoke_task' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/application.rb:116:in block (2 levels) in top_level' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/application.rb:116:in each' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/application.rb:116:in block in top_level' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/application.rb:125:in run_with_threads' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/application.rb:110:in top_level' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/application.rb:83:in block in run' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/application.rb:186:in standard_exception_handling' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/lib/rake/application.rb:80:in run' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/exe/rake:27:in <top (required)>' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/bin/rake:23:in load' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/bin/rake:23:in ' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/bin/ruby_executable_hooks:22:in eval' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/bin/ruby_executable_hooks:22:in ' Couldn't create database for {"adapter"=>"postgresql", "database"=>"prelaunchr_test", "host"=>"localhost"} rake aborted! Gem::LoadError: Specified 'postgresql' for database adapter, but the gem is not loaded. Add gem 'pg' to your Gemfile (and ensure its version is at the minimum required by ActiveRecord). /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/connection_adapters/connection_specification.rb:177:in rescue in spec' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/connection_adapters/connection_specification.rb:174:in spec' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/connection_handling.rb:50:in establish_connection' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/tasks/database_tasks.rb:109:in create_current' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/railties/databases.rake:17:in block (2 levels) in <top (required)>' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/exe/rake:27:in <top (required)>' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/bin/ruby_executable_hooks:22:in eval' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/bin/ruby_executable_hooks:22:in '

Caused by: Gem::LoadError: can't activate pg (~> 0.15), already activated pg-1.2.3. Make sure all dependencies are added to Gemfile. /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/connection_adapters/postgresql_adapter.rb:16:in <top (required)>' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activesupport-4.2.11.3/lib/active_support/dependencies.rb:274:in require' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activesupport-4.2.11.3/lib/active_support/dependencies.rb:274:in block in require' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activesupport-4.2.11.3/lib/active_support/dependencies.rb:240:in load_dependency' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activesupport-4.2.11.3/lib/active_support/dependencies.rb:274:in require' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/connection_adapters/connection_specification.rb:175:in spec' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/connection_handling.rb:50:in establish_connection' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/tasks/database_tasks.rb:109:in create_current' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/activerecord-4.2.11.3/lib/active_record/railties/databases.rake:17:in block (2 levels) in <top (required)>' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/gems/rake-13.0.6/exe/rake:27:in <top (required)>' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/bin/ruby_executable_hooks:22:in eval' /Users/sahrsaffa/.rvm/gems/ruby-2.5.3/bin/ruby_executable_hooks:22:in ' Tasks: TOP => db:create (See full trace by running task with --trace)

any help would be greatly appreciated.

Ruby on Rails allow multiple clicks for link_to

I'm new to Ruby on Rails and have found myself stumped.

I am trying to create a link_to item in my view that will not be disabled after being clicked once. It's a page listing people's names and their attendance. The names are colored red if absent and green if present and I'd like the user to be able to toggle the attendance more than once for each person.

Here is the code for my view and controller (note I am using websockets here as well to update the coloring of the button after being clicked):

index.html.erb:

    <div id="reader-attendance-<%= member.id %>">
      <% if member.present == true %>
          <%= link_to member.last_name.upcase, attendance_path(:id => member.id, :present => false), remote: true, class: "btn btn-outline-success btn-14" %>
      <% else %>
        <%= link_to member.last_name.upcase, attendance_path(:id => member.id, :present => true), remote: true, class: "btn btn-outline-danger btn-14" %>
      <% end %>
    </div>

controller.rb:

  def attendance
    member = Member.find(params[:id])
    if(params[:present] == 'true')
      member.present = true
    else
      member.present = false
    end
    member.save
    vote_member = VoteMember.where(member_name: member.display_name)[0]
    if vote_member.vote_type == 'Absent'
      vote_member.vote_type = ''
      vote_member.save
    end
    ActionCable.server.broadcast(
      'attendance_channel',
      {
        member_id: member.id,
        present: params[:present],
        vote_member_id: vote_member.id,
        total_abs: Member.where(present: false).count(),
        member_name: member.last_name.upcase
      }
    )
  end

Solutions I have tried:

  1. I've read that you can add an option to config so that the disable option is turned off as follows: Rails.application.configure do config.action_view.automatically_disable_submit_tag = false end The it seems like this is not supported, however, for the link_to tag and is only supported for button_to

  2. I added the content in #1 to config and then I've tried the button_to option as follows with no success. I have a feeling it's the way that I've passed the parameters in here:

  <%=button_to member.last_name.upcase ,:action => :attendance, :id => member.id, :present => false, remote: true, class: "btn btn-outline-success btn-14" %>

I am working with the following versions:

Rails 6.1.4.1 Ruby 3.0.1

Thanks in advance! Please let me know if other info would be helpful.

samedi 20 novembre 2021

How do I keep the dash in the humanize string

Keep dash for humanize hash key

  1. Replaces underscores with spaces if any.
  2. Capitalizes the first word.
  3. The left character and right character of the dash(-) is in Uppercase if any.

For example:

this_is_a_test -> This is a test

foo_bar -> Foo bar

rock-on-a-roll -> Rock-On-A-Roll

a_full-stack_dev -> A_Full-Stack_dev

vendredi 19 novembre 2021

Ruby get variable in another method (undefined local variable or method )

The function is to display the correct final price for each number. For example, if there are 5 bottles, it should get results for: 5 * 2 + 10 = 15

The enum example is:

class AaaBbb < ApplicationRecord

 enum number: { apple: 1, bottle: 2, headphone: 3, wallet: 5 }

The function to get value is like this :

def find_value(key)
  val = AaaBbb.numbers[key] # this will be nil if the key isn't found
  val || 0
end

The function to calculate the money is (HAS ERROR HERE, NEED TO UPDATE):

  def calculate
      quantity * find_value + 10
  end

Now it has an error:

undefined local variable or method `val' for #AaaBbb:0x00007f7cd9443240 Did you mean? eval Extracted source (around line #33):

   def calculate
     quantity * val + 10
   end

Question:

How to solve the problem by modifying the find_value or calculate functions? If you have any better ideas, please feel free to share.

Ruby on rails: function to find value by key

I just encountered a problem with ruby syntax:

The enum example is:

class AaaBbb < ApplicationRecord

 enum number: { a: 1, b: 2, c: 3, d: 5 }

or

class AaaBbb < ApplicationRecord

 enum number: { "a" => 1, "b" => 2, "c" => 3, "d" => 5 }

The function is:

  def find_value
    AaaBbb.numbers.each do |key, value|
        puts "#{key} = #{value}"
      if key == AaaBbb.numbers[:key] (WRONG CODE HERE, NEED TO FIX)
        return value
      else
        return 0
      end
    end
  end

So I am trying to write a function that if it finds the key, then return the value. For example that if I find look up some product(key), it will return the correct price(value) to display.

Thanks, and feel free to share if you have any better way to solve it.

fedena : rake aborted school not selected

I was installing fedena on ubuntu installed on wsl and the database creation and migration was successful but when run the command rake fedena:plugins:install_all to install the plugins. in the middle this error pops up that school Not Selected and here is the error trace.

School Not Selected
/root/fedena/vendor/plugins/acts_as_multi_school/lib/multischool/read.rb:46:in `with_school'
/root/fedena/vendor/plugins/acts_as_multi_school/lib/multischool/read.rb:22:in `find_with_school'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/activerecord-2.3.5/lib/active_record/base.rb:1954:in `find'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/activerecord-2.3.5/lib/active_record/base.rb:1954:in `find_or_create_by_config_key'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/activerecord-2.3.5/lib/active_record/base.rb:1940:in `send'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/activerecord-2.3.5/lib/active_record/base.rb:1940:in `method_missing_without_paginate'
/root/fedena/vendor/plugins/will_paginate/lib/will_paginate/finder.rb:170:in `method_missing'
/root/fedena/app/models/configuration.rb:90:in `find_or_create_by_config_key'
/root/fedena/db/seeds.rb:26
/root/fedena/db/seeds.rb:2:in `each'
/root/fedena/db/seeds.rb:2
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:145:in `load_without_new_constant_marking'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:145:in `load'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:521:in `new_constants_in'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:145:in `load'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rails-2.3.5/lib/tasks/databases.rake:215
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/lib/rake.rb:636:in `call'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/lib/rake.rb:636:in `execute'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/lib/rake.rb:631:in `each'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/lib/rake.rb:631:in `execute'
/root/fedena/lib/tasks/fedena_plugin_install.rake:31
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/lib/rake.rb:636:in `call'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/lib/rake.rb:636:in `execute'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/lib/rake.rb:631:in `each'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/lib/rake.rb:631:in `execute'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/lib/rake.rb:597:in `invoke_with_call_chain'
/usr/local/rvm/rubies/ruby-1.8.7-p374/lib/ruby/1.8/monitor.rb:242:in `synchronize'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/lib/rake.rb:590:in `invoke_with_call_chain'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/lib/rake.rb:583:in `invoke'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/lib/rake.rb:2051:in `invoke_task'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/lib/rake.rb:2029:in `top_level'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/lib/rake.rb:2029:in `each'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/lib/rake.rb:2029:in `top_level'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/lib/rake.rb:2068:in `standard_exception_handling'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/lib/rake.rb:2023:in `top_level'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/lib/rake.rb:2001:in `run'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/lib/rake.rb:2068:in `standard_exception_handling'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/lib/rake.rb:1998:in `run'
/usr/local/rvm/gems/ruby-1.8.7-p374/gems/rake-0.8.7/bin/rake:31
/usr/local/rvm/gems/ruby-1.8.7-p374/bin/rake:19:in `load'
/usr/local/rvm/gems/ruby-1.8.7-p374/bin/rake:19

the code causing this error appears to be this code:

module MultiSchool

  module Read

    def self.extended (base)
      
      eigen_class = class << base;self;end
      
      ["find","count","sum","exists?"].each do |method|
        
        matches = method.match /([\w\d_]+)(\?|!|=)?$/
        
        eigen_class.send :define_method, "#{matches[1]}_with_school#{matches[2]}" do |*args|

          options = args.extract_options!
          skip_multischool = options.delete :skip_multischool
          args << options unless options.empty?
          
          result = if skip_multischool || Thread.current[:skip_multischool].present?
            send("#{matches[1]}_without_school#{matches[2]}",*args)
          else
            with_school do
              send("#{matches[1]}_without_school#{matches[2]}",*args)
            end
          end
          result
        end

        eigen_class.send :alias_method_chain, method, :school
      end

    end

    def skip_multischool
      Thread.current[:skip_multischool]=true
      yield
    ensure
      Thread.current[:skip_multischool]=nil
    end

    private

    def with_school      
      target_school = MultiSchool.current_school
      if target_school.nil?
        raise MultiSchool::Exceptions::SchoolNotSelected,"School Not Selected"
      else
        with_scope(:find => {:conditions  => {:school_id  => target_school.id}}) do
          yield
        end
      end
    end

  end

end

looks the MultiSchool.current_school is returning nil which sets the variable target_school to nil so the above exception occurs of school not selected but I don't know where to from here?

Could you please help me out this issue.

How can I retrieve Basic Authentication credentials from the header in ruby?

Can anyone explain to me how to get a username and password from a request header in ruby?

jeudi 18 novembre 2021

Rails Ransack gem: search for multiple values with one condition

I use ransack gem and I have a select field event_id,if choose option Event Online will search with multiple values. This is my query:

ransack("job_name_cont" => job_name, "event_id_eq" => event_id).result

event_ids is string or array - eg: 90 or [ 145, 147, 148 ]. When search with option Event Online, the result returning errors:

[1] pry(Job)> ransack("job_name_cont" => job_name, "event_id_eq" => event_ids).result 
NoMethodError: undefined method `to_i' for [145, 147, 148]:Array
Did you mean?  to_s
               to_a
               to_h

My model:

class Job < ActiveRecord::Base
  belongs_to :event
end

class Event < ActiveRecord::Base
  has_many :jobs, dependent: :destroy
end

How can i search with event_id is array?

mercredi 17 novembre 2021

attr_encrypted gem sometimes saving null value in database

I am running rails 3 version and using attr_encrypted gem version '1.2.1' . sometimes i have seen that nil entry is getting stored into column encrypted_private_key.

Below is my model

class Device < ActiveRecord::Base
  attr_encrypted :private_key, :key => proc {|device| device.log }
end

Below is how i am trying to store value in column encrypted_private_key

device = Device.new
device.private_key = "XYZ" 
device.save

after doing device.save if i do device.encrypted_private_key then sometimes i am getting nil value. what could be the reason for this? This issue is not coming everytime but sometime.

getting user info using JWT Token in ruby

I want to extract user info like User ID and User Name using JWT token. I was able to do it in django like this-

    valid_data = TokenBackend(algorithm='HS256').decode(token, verify=False)
    user_id = valid_data['user_id']
    return user_id

but how do I do it using ruby. Thanks :)

mardi 16 novembre 2021

Ruby On Rails executing with wrong version

I try to Run my new rails app using RubyMine, and it seems to use some wrong Ruby version and i can't figure out why! I used rbenv to setup the environment .ruby-version shows 3.0.2

/bin/zsh -c "bash -c 'env RBENV_VERSION=2.7.2 /usr/local/Cellar/rbenv/1.2.0/libexec/rbenv exec ruby /Users/ran/source/rails/MySite/bin/rails server -b 0.0.0.0 -p 3000 -e development'" Your Ruby version is 2.7.2, but your Gemfile specified 3.0.2

ran@ran-mac MySite % ruby --version ruby 3.0.2p107 (2021-07-07 revision 0db68f0233) [x86_64-darwin20] ran@ran-mac MySite %

What's wrong? I can not understand where it takes this 2.7.2 from! Thanks

lundi 15 novembre 2021

Error installing ruby 2.7.0 with rvm and openssl

I want to install ruby 2.7.0 and compile it with openssl. So, I did the following:

rvm package install openssl
rvm install 2.7.0 --with-openssl-dir=/home/arnab/.rvm/usr

Here, $HOME=/home/arnab But, it gives the error and the make.log shows:

/usr/bin/ld: /home/arnab/.rvm/usr/lib/libssl.a(s23_meth.o): Relocation R_X86_64_32 against 'ro.data' can not be used when making a shared object; recompile with -fPIC
/home/arnab/.rvm/usr/lib/libssl.a :error adding symbol: Bad value

Well, it tells me recompile with fPIC but how do I do that? Any help is appreciated.

dimanche 14 novembre 2021

Rails 3 uninitialized constant when using thread

i am running rails 3 thread to improve the performance of the rake task. sometimes i am getting uninitialized constant when i am trying to access outside class from my current class. as an example when i am trying to access NotificationService class from NotificationApp as shown below then getting error as uninitialized constant NotificationService. This error is not coming every time. sometimes rake task is running fine without the error and sometimes same rake is failing with uninitialized constant. what could be the reason for this and how can i fix this issue?

class NotificationApp < ActiveRecord::Base
  def signal_event
    NotificationService.notify
  end
end

vendredi 12 novembre 2021

How to maintain a copy of a hash with original values after changing some of its values in ruby?

I have tried to phrase this to the best of my ability. I have a hash that I perform some operations on but before I do this, I store this hash in another variable. Now when I access this variable, the values seem to have changed, how can I go around it. Example:

hash = {a: "1", b: "2", c: "3"}
hash_copy = hash
hash["a"]=4
puts(hash_copy["a"]) #prints 4 instead of 1

How can I get the put statement to print 1 instead of 4, that is, print the original value.

Updating to Ruby 3.0.x with Rails: symbol not found in flat namespace '_RHASH_EMPTY_P'

Having issues upgrading my rails project on my M1 Mac related to Debase not compiling due to symbol not found in flat namespace '_RHASH_EMPTY_P'

OS: Monterey 12.0.1 Machine: Mac mini (m1, 2020) Ruby version: 3.0.2 Rails: 6.1.4.1

I've tried removing Gemfile.lock and totally reinstalling brew/rbenv/rails. The app runs successfully on the Ruby:3.0.2 docker image.

When I run rails s, I get the following stack trace:

/Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `require': dlopen(/Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/debase-0.2.4.1/lib/debase_internals.bundle, 0x0009): symbol not found in flat namespace '_RHASH_EMPTY_P' - /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/debase-0.2.4.1/lib/debase_internals.bundle (LoadError)
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `block in require_with_bootsnap_lfi'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/loaded_features_index.rb:92:in `register'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require_with_bootsnap_lfi'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:31:in `require'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/activesupport-6.1.4.1/lib/active_support/dependencies.rb:332:in `block in require'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/activesupport-6.1.4.1/lib/active_support/dependencies.rb:299:in `load_dependency'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/activesupport-6.1.4.1/lib/active_support/dependencies.rb:332:in `require'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/debase-0.2.4.1/lib/debase.rb:4:in `<main>'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `require'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `block in require_with_bootsnap_lfi'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/loaded_features_index.rb:92:in `register'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require_with_bootsnap_lfi'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:31:in `require'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/activesupport-6.1.4.1/lib/active_support/dependencies.rb:332:in `block in require'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/activesupport-6.1.4.1/lib/active_support/dependencies.rb:299:in `load_dependency'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/activesupport-6.1.4.1/lib/active_support/dependencies.rb:332:in `require'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/ruby-debug-ide-0.7.3/lib/ruby-debug-ide.rb:9:in `<main>'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `require'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `block in require_with_bootsnap_lfi'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/loaded_features_index.rb:92:in `register'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require_with_bootsnap_lfi'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:31:in `require'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bundler-2.2.31/lib/bundler/runtime.rb:60:in `block (2 levels) in require'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bundler-2.2.31/lib/bundler/runtime.rb:55:in `each'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bundler-2.2.31/lib/bundler/runtime.rb:55:in `block in require'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bundler-2.2.31/lib/bundler/runtime.rb:44:in `each'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bundler-2.2.31/lib/bundler/runtime.rb:44:in `require'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bundler-2.2.31/lib/bundler.rb:175:in `require'
    from /Users/josh/Documents/Development/hub/config/application.rb:20:in `<main>'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `require'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `block in require_with_bootsnap_lfi'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/loaded_features_index.rb:92:in `register'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require_with_bootsnap_lfi'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:31:in `require'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/activesupport-6.1.4.1/lib/active_support/dependencies.rb:332:in `block in require'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/activesupport-6.1.4.1/lib/active_support/dependencies.rb:299:in `load_dependency'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/activesupport-6.1.4.1/lib/active_support/dependencies.rb:332:in `require'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/railties-6.1.4.1/lib/rails/commands/server/server_command.rb:138:in `block in perform'
    from <internal:kernel>:90:in `tap'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/railties-6.1.4.1/lib/rails/commands/server/server_command.rb:135:in `perform'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/thor-1.1.0/lib/thor/command.rb:27:in `run'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/thor-1.1.0/lib/thor/invocation.rb:127:in `invoke_command'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/thor-1.1.0/lib/thor.rb:392:in `dispatch'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/railties-6.1.4.1/lib/rails/command/base.rb:69:in `perform'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/railties-6.1.4.1/lib/rails/command.rb:48:in `invoke'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/railties-6.1.4.1/lib/rails/commands.rb:18:in `<main>'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `require'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `block in require_with_bootsnap_lfi'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/loaded_features_index.rb:92:in `register'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require_with_bootsnap_lfi'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:31:in `require'
    from /Users/josh/Documents/Development/hub/bin/rails:9:in `<top (required)>'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/spring-2.1.1/lib/spring/client/rails.rb:28:in `load'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/spring-2.1.1/lib/spring/client/rails.rb:28:in `call'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/spring-2.1.1/lib/spring/client/command.rb:7:in `call'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/spring-2.1.1/lib/spring/client.rb:30:in `run'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/spring-2.1.1/bin/spring:49:in `<top (required)>'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/spring-2.1.1/lib/spring/binstub.rb:11:in `load'
    from /Users/josh/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/spring-2.1.1/lib/spring/binstub.rb:11:in `<top (required)>'
    from <internal:/Users/josh/.rbenv/versions/3.0.2/lib/ruby/3.0.0/rubygems/core_ext/kernel_require.rb>:85:in `require'
    from <internal:/Users/josh/.rbenv/versions/3.0.2/lib/ruby/3.0.0/rubygems/core_ext/kernel_require.rb>:85:in `require'
    from /Users/josh/Documents/Development/hub/bin/spring:15:in `<top (required)>'
    from bin/rails:3:in `load'
    from bin/rails:3:in `<main>'

uninitialized constant Rails::Plugin::Authorization when run `rake db:migrate`

I was populating a rails application fedena database with the command rake db:migrate, I am getting an error:

rake aborted! uninitialized constant Rails::Plugin::Authorization

when I tried to run the rake command with --trace I got the following:

** Execute environment
rake aborted!
uninitialized constant Rails::Plugin::Authorization
/usr/local/rvm/gems/ruby-1.8.7-head/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:105:in `const_missing'
/mnt/c/users/usrx/Documents/myapp/app/vendor/plugins/acts_as_multi_school/init.rb:15:in `evaluate_init_rb'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rails-2.3.5/lib/rails/plugin.rb:158:in `evaluate_init_rb'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/activesupport-2.3.5/lib/active_support/core_ext/kernel/reporting.rb:11:in `silence_warnings'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rails-2.3.5/lib/rails/plugin.rb:154:in `evaluate_init_rb'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rails-2.3.5/lib/rails/plugin.rb:48:in `load'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rails-2.3.5/lib/rails/plugin/loader.rb:38:in `load_plugins'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rails-2.3.5/lib/rails/plugin/loader.rb:37:in `each'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rails-2.3.5/lib/rails/plugin/loader.rb:37:in `load_plugins'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rails-2.3.5/lib/initializer.rb:369:in `load_plugins'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rails-2.3.5/lib/initializer.rb:165:in `process'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rails-2.3.5/lib/initializer.rb:113:in `send'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rails-2.3.5/lib/initializer.rb:113:in `run'
/mnt/c/users/userx/Documents/myapp/app/config/environment.rb:5
/usr/local/rvm/gems/ruby-1.8.7-head/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:in `gem_original_require'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:in `require'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:in `require'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:521:in `new_constants_in'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:in `require'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rails-2.3.5/lib/tasks/misc.rake:4
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:636:in `call'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:636:in `execute'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:631:in `each'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:631:in `execute'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:597:in `invoke_with_call_chain'
/usr/local/rvm/rubies/ruby-1.8.7-head/lib/ruby/1.8/monitor.rb:242:in `synchronize'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:590:in `invoke_with_call_chain'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:607:in `invoke_prerequisites'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:604:in `each'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:604:in `invoke_prerequisites'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:596:in `invoke_with_call_chain'
/usr/local/rvm/rubies/ruby-1.8.7-head/lib/ruby/1.8/monitor.rb:242:in `synchronize'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:590:in `invoke_with_call_chain'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:583:in `invoke'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:2051:in `invoke_task'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:2029:in `top_level'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:2029:in `each'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:2029:in `top_level'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:2068:in `standard_exception_handling'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:2023:in `top_level'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:2001:in `run'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:2068:in `standard_exception_handling'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/lib/rake.rb:1998:in `run'
/usr/local/rvm/gems/ruby-1.8.7-head/gems/rake-0.8.7/bin/rake:31
/usr/local/rvm/gems/ruby-1.8.7-head/bin/rake:19:in `load'
/usr/local/rvm/gems/ruby-1.8.7-head/bin/rake:19
/usr/local/rvm/gems/ruby-1.8.7-head/bin/ruby_executable_hooks:22

I think the line causing the error is in the file init.rb which is:

Authorization::AUTH_DSL_FILES << "#{RAILS_ROOT}/vendor/plugins/acts_as_multi_school/config/acts_as_multi_school_auth.rb"

and I do not know how can this be solved!

jeudi 11 novembre 2021

Customize Fedena flash messages

How can I customize flash messages from Fedena? for example in the forgot page, when user supplies not existing username, it displays this message no username exists with username How can I customize that message to the user supplied does not exist! in the source code I see for example, this code flash[:notice] = "#{t('flash18')}". when traced the t() function. it redirects to the translator.rb which contains

module ActionController #:nodoc:
  class Base
    
    # Add a +translate+ (or +t+) method to ActionController that is context-aware of what controller and action
    # is being invoked. Initial scoping will be [:controller_name :action_name] when looking up keys. Example would be
    # +['posts' 'show']+ for the +PostsController+ and +show+ action.
    def translate_with_context(key, options={})
      Translator.translate_with_scope([self.controller_name, self.action_name], key, options)
    end
  
    alias_method_chain :translate, :context
    alias :t :translate
  end
end

module ActiveRecord #:nodoc:
  class Base

    def translate(key, options={})
      Translator.translate_with_scope([self.class.name.underscore], key, options)
    end
  
    alias :t :translate
  
    # Add translate as a class method as well so that it can be used in validate statements, etc.
    class << Base
    
      def translate(key, options={}) #:nodoc:
        Translator.translate_with_scope([self.name.underscore], key, options)
      end
    
      alias :t :translate
    end
  end
end

but I don't see the string I was after i.e no user exists with username. How can I customize these messages in fedena?

mercredi 10 novembre 2021

Attachments adding duplicates in active storage

I have a Message model which has

 has_many_attached :attachments

My functions:

  def update_attachment
        remaining_attachment_ids = attachment_params[:existing]
        if message.attachments.attached? && errors.empty?
          message.attachments.where.not(id: remaining_attachment_ids).purge
          message.reload
          puts "AFTER DELETE"
          puts message.attachments.count
        end
        message.reload

        attach_new_files
      end

      def attach_new_files
        if attachment_params[:new]
          puts attachment_params[:new].map { |attachment| attachment["blob_signed_id"]}
          message.attachments.attach(attachment_params[:new].map { |attachment| attachment["blob_signed_id"] })
          message.reload
          puts "AFTER UPDATE"
          puts message.attachments.count
        end
      end

I'm trying to purge some and then add new attachments in a two step process. First I purge the attachments and the message.attachments.count is getting printed correctly.

However when I do attach_new_files, After the attachments I'm getting an extra count. For example, I have only 2 items in attachment_params[:new] array. When I print the count after attaching, It's showing 3. I have supplied only 2 blob_signed_ids to attach. What might be the issue here?

mardi 9 novembre 2021

Problem with remote Button method post to redirect in controller

My problem: When place is not present controller does not redirect to the route i want.

I have a link_to , check_payer post route

<%= link_to "Click here", check_payer_path, method: :post, remote: true %>

this methods verify if place is present and if true is not redirecting to billings_path

  def check_payer
    if @place.present?
      redirect_to billings_path
    end
  end

If place is not present it will render check_payer.js.erb that opens a form modal.

$('#modal-check-payer').find(".modal-content").html("<%= j render partial:'place_billing_infos/check_payer_modal' %>");
$("#modal-check-payer").modal();

And this nested form call update_payer_path patch.

<%= simple_nested_form_for @place_billing_info, url: update_payer_path, html: { 
autocomplete: 'off', class: "form-horizontal" } do |place_form| %>

<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span 
aria-hidden="true">&times;</span></button>
<h4 class="modal-title" id="myModalLabel"><%= html_icon_member %> <span class="text- 
normal">Insira seu CPF/CNPJ para visualizar a fatura.</span></h4>
</div>

 <div class="modal-body">
 <div class="row">
  <div class="col-sm-12 text-muted">
    <%= place_form.simple_fields_for :billing_info do |info| %>
      <div class="col-md-4  col-xs-8 modal-text-left"><%= info.input :payer_cpfcnpj, 
 wrapper: :default_form, label: 'Cpf/Cnpj', required: true %></div>
     <% end %>
   </div>
 </div>
</div>

<div class="modal-footer">
<button type="submit" class="btn btn-info new-member-submit">Exibir fatura</button>
</div>
<% end %>

Getting error trying to start ruby on rails

I created a new app with ruby on rails and tried to start it, then got this error.

1 - have ruby-dev-kit

2 - ruby version 2.7.0

Tried to fix this error in many ways. I use Linux

Traceback

       11: from /usr/lib/ruby/2.7.0/psych/nodes.rb:2:in `<main>'
        10: from /var/lib/gems/2.7.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:31:in `require'
         9: from /var/lib/gems/2.7.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require_with_bootsnap_lfi'
         8: from /var/lib/gems/2.7.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/loaded_features_index.rb:92:in `register'
         7: from /var/lib/gems/2.7.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `block in require_with_bootsnap_lfi'
         6: from /var/lib/gems/2.7.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `require'
         5: from /usr/lib/ruby/2.7.0/psych/nodes/node.rb:2:in `<main>'
         4: from /var/lib/gems/2.7.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:31:in `require'
         3: from /var/lib/gems/2.7.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require_with_bootsnap_lfi'
         2: from /var/lib/gems/2.7.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/loaded_features_index.rb:92:in `register'
         1: from /var/lib/gems/2.7.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `block in require_with_bootsnap_lfi'
/var/lib/gems/2.7.0/gems/bootsnap-1.9.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `require': superclass mismatch for class StringIO (TypeError)

ActiveStorage::FileNotFoundError in direct upload Attach using Amazon s3 presigned url

I'm using presigned_post for generating signed_url to upload file to s3 directly from client. The file is getting uploaded correctly and returning response with a generated blob_signed_id.

However , when I try to attach the file to the object , it is showing FileNotFoundError.

  def generate_url
    load_aws_credentials
    load_bucket
    blob = create_blob
    presigned_url = @s3_bucket.presigned_post(
      key: "#{Rails.env}/#{SecureRandom.uuid}/${filename}",
      success_action_status: "201",
      signature_expiration: (Time.now.utc + 15.minutes),
    )
    response = { url: presigned_url.url, url_fields: presigned_url.fields }
    response[:blob_signed_id] = blob.signed_id
    response
  end

  private
    attr_reader :blob_args

    def create_blob
      blob = ActiveStorage::Blob.create_before_direct_upload!(**blob_args)
      blob
    end 

The blob is getting created and a signed_id is returned.

 def take_actions
        @message = ::Widget::Message.new(message_params)
        attach_files
        if @message.save
         ...
        else
         ...
        end
      end

  def attach_files
      if data["attachments"]
        data["attachments"].map do |attachment|
          @message.attachments.attach(attachment["blob_signed_id"])
        end
      end
    end

When I try to attach the file using the signed_id it is showing file not found.

Presigned url upload and linking using active storage

I'm trying to upload attachments via AWS s3 presigned url. It is done as a 2 step process . First I created an API for generating a presigned post url and sent to client React App.

class Admin::PresignedUploadController < ApplicationController
  before_action :authenticate_user!, only: [:index]
  before_action :load_aws_credentials, only: [:index]
  before_action :load_bucket, only: [:index]

  def index
    presigned_url = @s3_bucket.presigned_post(
      key: "#{Rails.env}/#{SecureRandom.uuid}/${filename}",
      success_action_status: "201",
      signature_expiration: (Time.zone.now.utc + 15.minutes)
    )

    data = { url: presigned_url.url, url_fields: presigned_url.fields }

    render json: data, status: :ok
  end

  private

    def load_bucket
      @s3_bucket = Aws::S3::Resource.new(
        region: ENV["AWS_REGION"],
        credentials: @aws_credentials
      ).bucket(ENV["AWS_BUCKET_NAME"])
    end

    def load_aws_credentials
      @aws_credentials = Aws::Credentials.new(
        ENV["AWS_ACCESS_KEY_ID"],
        ENV["AWS_SECRET_ACCESS_KEY"]
        )
    end
end

I'm able to upload the file via a post request to the url and get a response from s3.

<PostResponse>
    <Location>https://neeto-chat-staging-v1.s3.amazonaws.com/development%2Fa185e6a8-b4eb-402e-a11a-a2c8ed48bdea%2Fwallpaper-photos-3.jpg</Location>
    <Bucket>neeto-chat-staging-v1</Bucket>
    <Key>development/a185e6a8-b4eb-402e-a11a-a2c8ed48bdea/wallpaper-photos-3.jpg</Key>
    <ETag>"2cbc861b2a9e0c48c7a7edf565f6a509"</ETag>
</PostResponse>

My first problem is that the Location is not accessible and it is showing access denied. I hope it might get solved after giving GET permission in AWS s3.

Is the Location returning the public url of the file?

Do I have to make an additional request to attach it to the model using active record or can it be done automatically using active record?

My schema for attachments:

  create_table "active_storage_attachments", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
    t.string "name", null: false
    t.string "record_type", null: false
    t.uuid "record_id", null: false
    t.uuid "blob_id", null: false
    t.datetime "created_at", null: false
    t.index ["blob_id"], name: "index_active_storage_attachments_on_blob_id"
    t.index ["record_type", "record_id", "name", "blob_id"], name: "index_active_storage_attachments_uniqueness",
unique: true
  end

My model Message has:

 has_many_attached :attachments

 def get_url(attachment)
      Rails.application.routes.url_helpers.rails_blob_path(
        attachment, only_path: true
      )
    end

def get_attachments
  if attachments.attached?
    self.attachments.attachments.map do |attachment|
      {
        filename: attachment.filename,
        url: get_url(attachment),
        id: attachment.id
      }
    end
  end
end

dimanche 7 novembre 2021

Rails 5: Is Nested forms set up correct

If I want a Nested Form for volunteer_shift inside my assignment/_form

How should my model associations be set up?

My current associations look like this..but I am not sure they are correct if the volunteer_shift partial sits inside the assignment form....

When I try to open the "add new record" form...my assignment#new action errors out...

error message

Completed 500 Internal Server Error in 30ms (ActiveRecord: 2.7ms)



NoMethodError - undefined method `build' for nil:NilClass:
  app/controllers/assignments_controller.rb:21:in `new'

Here is my new action...

  # GET /assignments/new
  def new
    @assignment = Assignment.new
    # binding.pry
    @assignment.volunteer_event.build   <----Line 21
    @my_url = {:action => "create", :id => params[:id]}
  end

Here are my current models associations...

class Assignment < ApplicationRecord
  attr_accessor :volunteer_event
  belongs_to :volunteer_shift
  has_one :volunteer_task_type, :through => :volunteer_shift, :source => :volunteer_task_type
  belongs_to :contact ,optional: true
  validates_presence_of :volunteer_shift #belongs_to takes care of this now
  validates_associated :volunteer_shift
  accepts_nested_attributes_for :volunteer_shift, allow_destroy: true
...
class VolunteerShift < ApplicationRecord
  has_many :assignments
  belongs_to :volunteer_event
...

class VolunteerEvent < ApplicationRecord
  belongs_to :volunteer_default_event
  has_many :volunteer_shifts, :dependent => :destroy
  has_many :resources_volunteer_events, :dependent => :destroy
  validates_associated :volunteer_shifts

And inside my assignment/form

<%= form_for @assignment, :url => @my_url, remote: true do |f| %>
...
          <!--VOLUNTEER SHIFT-->
          <!--TODO: make this a partial under field_for-->
          <%= f.fields_for :volunteer_shift do |builder| %>
            <%= render 'volunteer_shift_fields', vs: builder %>
          <% end %>
...
<% end %>

and if you want to see the volunteer_shift_fields partial


<div class="name large flex-row">
  <%= vs.label :volunteer_shift %>
</div>
<div id="volunteer_shift" class="d-flex flex-row">
  <div class="col-sm-12 p-2">
    <div id="volunteer_shift" class="text-right">
      <!-- old if: if class is assignment show volunteer shift else show default shift -->
      <!--  we need default shift here...NO assignment is attached-->
      <div class="field">
        <%= vs.label :volunteer_task_type_id %>
        <%= select_tag 'volunteer_task_type_id', options_from_collection_for_select([VolunteerTaskType.new(:description => ""),  VolunteerTaskType.instantiables.effective_on(Date.today)].flatten, "id", "description")  %>
      </div>
      <div class="field">
        <%= vs.label :roster_id %>
        <%= select_tag 'roster_id', options_from_collection_for_select([Roster.new(:name => ""), Roster.all].flatten, "id", "name") %>
      </div>
      <div class="field">
        <%= vs.label :program_id %>
        <%= select_tag 'program_id', options_from_collection_for_select([Program.new(:name => ""), Program.where(:volunteer => true)].flatten, "id", "name")%>
      </div>
      <div class="field">
        <%= vs.label :set_description %>
        <%= vs.text_field(:set_description, nil) %>
      </div>
      <div class="field">
        <%= vs.label :set_date, "Date" %> <
        <%= vs.text_field(:set_date, nil) %>
      </div>
    </div>
  </div>
</div>

Are my model associations correct? What is my "assignment#new" action missing?

samedi 6 novembre 2021

How to read realtime ActiveRecord in Ruby on Rails

I want to read DATA which I have recently save in rails console to show up on my index page by real time.

  • Rails 6.1.4
  • Ruby 2.7.0

How should I do? or Does anyone have got a solution for making this?

vendredi 5 novembre 2021

Is there a way to access files that Rails has minified and compressed externally?

I know that the Rails asset pipeline will, under normal circumstances, minify and compress all JS files into one, making them smaller/obfuscated but impossible to access directly from another site. I also know that the /public folder contains files that bypass this process, and can be accessed directly by URL.

My question is, is there a way in Rails to combines these processes? Can I minify/compress a file using my Ruby on Rails gems and have it still be accessible by a static URL? I'm aware that I can place JS files in app/assets to have them go through the pipeline, but if I do that will they be accessible externally?

mardi 2 novembre 2021

How can I easily review a server installed dependencies for unpatched plugins?

I am working on a server migration and upgrade, and I don't code in Ruby at all.

Is there an easy way for me to scan / review the gemfile / installed dependencies to check that latest updated / unpatched dependencies?

The code references to a hundred at least dependencies and I am not sure which are no longer the latest stable version.

Rails5 method is not getting called from create action

So I have an old app I'm updating to Rails 5.0.7 (reasons)

I've ported over the original code bases "create" method but this line is giving me grief...

def create
...
    vs.attributes=(params["assignment"]["volunteer_shift_attributes"]) <--- WHY HE NOT CALLED ???
...
end

Note that ["assignment"]["volunteer_shift_attributes"]?

Well in the old code base the assignment model has this method (which I also ported over to the Rails 5 app)...

  def volunteer_shift_attributes=(attrs)
    self.volunteer_shift.attributes=(attrs) 
  end

So I'm guessing this is where is "supposed" to be getting called in the old app... ...but in the new Rails 5 app's assignment model it is not getting called. And I do not know why.

Here is the entire create action...


  def create # FIXME: evil brought over from original code base
    ve = nil
    if !params["id"].blank?
      ve = VolunteerEvent.find(params["id"])
    else
      if params["roster_id"].blank? || params["assignment"]["set_date"].blank?
        ve = VolunteerEvent.new # won't save
      else
        ve = Roster.find_by_id(params["roster_id"]).vol_event_for_date(params["assignment"]["set_date"])
      end
    end
    vs = ve.volunteer_shifts.new
    #    vs.slot_count = 1
    #    vs.volunteer_event_id = ve.id
    #    vs.volunteer_event = ve
    vs.stuck_to_assignment = vs.not_numbered = true
    vs.attributes=(params["assignment"]["volunteer_shift_attributes"]) <--- WHY HE NOT CALLED ???
    a = vs.assignments.new
    a.volunteer_shift = vs
    #    a.volunteer_shift_id = vs.id
    a.attributes = (params["assignment"])
    @assignments = vs.assignments = [a]
    vs.set_values_if_stuck
    vs.assignments = []
    @success = a.valid? && vs.save
    rt = params[:assignment].delete(:redirect_to)
    @my_url = {:action => "create_shift", :id => params[:id]}
    @assignment = a
    if @success
      vs = vs.reload
      @assignment = a = vs.assignments.new
      a.volunteer_shift = vs
      #    a.volunteer_shift_id = vs.id
      a.attributes = (params["assignment"])
      @assignments = vs.assignments = [a]

      if !@success
        vs.destroy
      end
    end
    if @success # and @assignment.volunteer_shift.save
      redirect_skedj(rt, ve.date_anchor)
    else
      # render :partial => 'assignments/new'
      render :partial => 'assignments/edit' #<--original
    end
  end


Here is the entire assignment model, the offending method is around line 117 (a lot of original code I've refactored for Rails 5...apologies for it's length, it is inherited code..adding here in case it is helpful)...

class Assignment < ApplicationRecord
  belongs_to :volunteer_shift
  has_one :volunteer_task_type, :through => :volunteer_shift, :source => :volunteer_task_type
  belongs_to :contact
  validates_presence_of :volunteer_shift
  validates_associated :volunteer_shift
  belongs_to :attendance_type
  belongs_to :call_status_type
  validates_presence_of :set_date, :if => :volshift_stuck
  validates_existence_of :contact, :allow_nil => true

  delegate :set_date, :set_date=, :to => :volunteer_shift
  delegate :set_description, :set_description=, :to => :volunteer_shift

  scope :date_range, lambda { |range|
    joins(volunteer_shift: :volunteer_event)
        .where(volunteer_shifts: { volunteer_events: { date: range } })
  }
  scope :is_after_today, lambda {||
    { :conditions => ['(SELECT date FROM volunteer_events WHERE id = (SELECT volunteer_event_id FROM volunteer_shifts WHERE id = assignments.volunteer_shift_id)) > ?', Date.today] }
  }
  scope :on_or_after_today, lambda {||
    { :conditions => ['(SELECT date FROM volunteer_events WHERE id = (SELECT volunteer_event_id FROM volunteer_shifts WHERE id = assignments.volunteer_shift_id)) >= ?', Date.today] }
  }
  scope :not_cancelled, -> { where('(attendance_type_id IS NULL OR attendance_type_id NOT IN (SELECT id FROM attendance_types WHERE cancelled = \'t\'))')}
  scope :roster_is_limited_by_program, -> {where("roster_id IN (SELECT id FROM rosters WHERE limit_shift_signup_by_program = 't')").joins(:volunteer_shift)}

  attr_accessor :attendance_type_id



  
  def real_programs
    return [] unless self.volunteer_shift&.roster
    return [] unless self.volunteer_shift.roster.limit_shift_signup_by_program
    self.volunteer_shift.roster.skeds.select{|x| x.category_type == "Program"}.map{|x| x.name}
  end


  def time_range_s
    return "" unless start_time and end_time
    (start_time.strftime("%I:%M") + ' - ' + end_time.strftime("%I:%M")).gsub( ':00', '' ).gsub( ' 0', ' ').gsub( ' - ', '-' ).gsub(/^0/, "")
  end

  def description
    self.volunteer_shift.volunteer_event.date.strftime("%D") + " " + self.time_range_s + " " + self.slot_type_desc
  end

  def roster_title
    self.volunteer_shift.roster.name
  end

  def date
    self.volunteer_shift.date
  end

  def event_date
    date
  end

  def slot_type_desc
    b = (self.volunteer_shift.volunteer_task_type_id.nil? ? self.volunteer_shift.volunteer_event.description : self.volunteer_shift.volunteer_task_type.description)
    b = b + " (#{self.volunteer_shift.description})" if self.volunteer_shift.description and self.volunteer_shift.description.length > 0
    b
  end

  def display_name
    ((!(self.volunteer_shift.description.nil? or self.volunteer_shift.description.blank?)) ? self.volunteer_shift.description + ": " : "") + self.contact_display
  end

  def cancelled?
    (self.attendance_type&.cancelled)
  end

  def attended?
    (self.attendance_type and !self.attendance_type.cancelled)
  end

  def contact_display
    if self.closed
      "(closed)"
    elsif contact_id.nil?
      return "(available)"
    else
      self.contact.display_name + "(#{self.voltask_count})"
    end
  end

  def <=>(other)
    self.date <=> other.date
  end

  def contact_id=(new_val)
    self.write_attribute(:contact_id, new_val)
    self.contact = Contact.find_by_id(new_val.to_i)
  end

  def contact_id_and_by_today
    # Unless the contact id is empty, or the event date is after today.
    !(contact_id.nil? || self.volunteer_shift.volunteer_event.date > Date.today)
  end

  def voltask_count
    self.contact_volunteer_task_type_count ? self.contact_volunteer_task_type_count.attributes["count"] : 0
  end

  before_validation :set_values_if_stuck
  def set_values_if_stuck
    return unless volshift_stuck
    volunteer_shift.set_values_if_stuck(self)
  end

  after_destroy { |record| if record.volunteer_shift&.stuck_to_assignment; record.volunteer_shift.destroy; else VolunteerShift.find_by_id(record.volunteer_shift_id).fill_in_available; end}
  after_save {|record| if record.volunteer_shift&.stuck_to_assignment; record.volunteer_shift.save; end}
  after_save { |record| VolunteerShift.find_by_id(record.volunteer_shift_id).fill_in_available }

  def volunteer_shift_attributes=(attrs) #fixme: why is this not getting called on volunteer_events/create_shift?
    self.volunteer_shift.attributes=(attrs) # just pass it up
  end


  def volshift_stuck
    self.volunteer_shift&.stuck_to_assignment
  end

  def first_time_in_area?
    if self.contact and self.volunteer_shift and self.volunteer_shift.volunteer_task_type
      !ContactVolunteerTaskTypeCount.has_volunteered?(self.contact_id, self.volunteer_shift.volunteer_task_type_id)
    else
      false
    end #  and self.contact_id_changed? moved outside because we use update_attributes
  end


  def all_day_event?
    self.start_time == self.start_time.midnight && self.end_time == self.end_time.midnight ? true : false
  end
end

What am I missing? Why is volunteer_shift_attributes nil when called inside the create action? Why is...

  def volunteer_shift_attributes=(attrs)
    self.volunteer_shift.attributes=(attrs) 
  end

...not getting called?

Thank you for your time.