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