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.