Posts

Showing posts with the label rails scope

What are delegate, delegate method, SimpleDelegator in ruby

 delegate methods in Rails, exposing only necessary methods of containing objects, thereby, making them more easily accessible. class Parent   def initialize     @child = Child.new   end end class Child   def initialize     @data = []   end   def insert(data)     @data << data   end   def fetch(key)     @data[key]   end end parent = Parent.new if you try this parent.insert("imrahul") then you will get response undefined method `insert' for #<Parent:0x000055f4915673a0 @child=#<Child:0x000055f491567350 @data=[]>> (NoMethodError)   This code will work if we overide methods of child class class Parent   def initialize     @child = Child.new   end   def insert(data)     @child.insert(data)   end   def fetch(index)     @child.fetch(index)   end end class Child   def initialize     @data = []   end   def insert(data)     @data << data   end   def fetch(key)     @data[key]   end end parent = Parent.new parent.insert("imrahul") So this is how dele

Setup a cron job or scheduler for your rails application using whenever gem.

cd path to your project. gem 'whenever', require: false   add it to your gemfile run bundle install bundle exec wheneverize .   //This will create an initial config/schedule.rb Now create your job call it  from config/schedule.rb whenever --update-crontab   //update crontab crontab -l   //list all cron job set :output, "log/cron.log"    //if you want to set log file for cron job then that this line at the top of config/schedule.rb         in production server:                   after deployment :  bundle exec whenever whenever --update-crontab crontab -l source: https://github.com/javan/whenever https://www.rubyguides.com/2019/04/ruby-whenever-gem/

rails scope with argument or dynamic value and join tables

scope :get_by_currency, -> (currency) {find_by(currency_id: currency)} scope :by_role, ->(role) { joins(:roles).where(roles: { name: role }) } //it will work in rails 4 and previous version scope :by_role, ->(role) { joins(:roles).where('roles.name ? ', #{role} ) } //it will work in all versions of rails validate  :validate_mimimum_amount, unless: -> (order) { order.ord_type=='market' || order.ord_type=='manual' }