Posts

Showing posts with the label rails 2

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/

unable to install ruby 2.2 in ubuntu 18.04

Try with this commands 1) Install rvm following instructions for Ubuntu on  https://github.com/rvm/ubuntu_rvm 2) rvm install ruby 2.2.10 3) rvm install ruby 2.2.10 --with-gcc=gcc if its not work then try with this  1. sudo apt purge libssl-dev && sudo apt install libssl1.0-dev 2. rvm install 2.3.5 --autolibs=disable

Authentication via JWT in rails api's

gem 'jwt' add this gem to your gem file bundle install create a file in lib/json_web_token.rb and paste following code class JsonWebToken      SECRET_KEY = Rails.application.secrets.secret_key_base. to_s      def self.encode(payload, exp = 15.days.from_now)         payload[:exp] = exp.to_i        JWT.encode(payload, SECRET_KEY)      end     def self.decode(token)        decoded = JWT.decode(token, SECRET_KEY)[0]        HashWithIndifferentAccess.new decoded     end end create another file config/initializers/jwt.rb and paste following code require 'json_web_token' Now inside controller/api/v1/ we will a parent class for our all end-points: api/v1/api_controller.rb class Api::V1::ApiController < ActionController::Base      protect_from_forgery with: :null_session      def autheticate_user         header = request.headers['Authorization']         header = header.split(' ').last if header         begin             @decoded = JsonWebToken.decode

How to run local gems in rails || How to override gem's in rails

Create new gem in your rails app Standard is local gems are kept in Vendor folders Give path in your Gemfile EX: path 'vendor/local_gems' do #this is your gem folder   gem 'countries'  #your local gem name   gem 'country_select' # your another local gem end run bundle install

Write simple html text in into rails tags

You can write simple text inside rails tag like link_to button_tag, submit_tag, text_field_tag etc.. (raw("<strong class='text-danger'>Decline</strong")) example : <%= link_to  (raw("<strong class='text-danger'>Decline</strong")), welcome_path %>

how to make separate routes for different user in rails

how to make separate routes for different user in rails  Make another routes file in your config folder           config/routes/admin.rb   //i made new file routes/admin.rb inside config folder Now inside your config/routes.rb file paste this           class ActionDispatch::Routing::Mapper             def draw(routes_name)              instance_eval(File.read(Rails.root.join("config/routes/#{routes_name}.rb")))             end           end        // paste this code above this Rails.application.routes.draw line now side your main route file(config/routes.rb) make new routes for admin file like draw :admin Now config/routes.rb will be look like this Rails.application.routes.draw do   draw :admin end Now you can make routes for admin or admin dashboard separately inside your config/routes/admin.rb file resources :admin

ActiveRecord::Base.connection.execute, robust record execute in rails

ActiveRecord::Base.transaction do          ActiveRecord::Base.connection.execute("UPDATE deposits SET amount = #{params[:adjust_amount].to_f} WHERE type = '#{@deposit.type}' AND id = #{@deposit.id} AND currency_id = '#{@deposit.currency_id}'").as_json if params[:adjust_amount].present?          ## update comment          if params[:mt5_history_id].present?            mt5_withdraw_history = Mt5History.find_by_id(params[:mt5_history_id])            mt5_withdraw_history.update(comment: params[:comment])          end        end This do loop will run until all parameter will execute if any record updatation is failed due to some reason all previous record update will be rollback!   

Create worker in rails by sidekiq and redis

Add sidekiq to your Gemfile: Add this to your Gemfile gem 'sidekiq' Run bundle install bundle install Create worker rails g sidekiq:worker Test #will create app/workers/test_worker.rb class TestWorker   include Sidekiq::Worker   def perform(id, name)     # do something   end end Call worker without any time boundation TestWorker.perform_async(5, 'rahul') //use this anywhere from your rails app(controller, model, helpers..) Call worker within particular time period TestWorker.perform_in(5.minutes, 5, 'rahul')  //use this anywhere from your rails app(controller, model, helpers..) Call worker after specific time interval once only TestWorker.perform_at(5.minutes.from_now, 5, 'rahul')  //use this anywhere from your rails app(controller, model, helpers..) Start sidekiq on development bundle exec sidekiq Start sidekiq on production bundle exec sidekiq -d //run this first if you get some error then use second one bundle exec si

An error occurred while installing nokogiri (1.8.4), and Bundler cannot continue.

An error occurred while installing nokogiri (1.8.4), and Bundler cannot continue. Try this first and then bundle install again   sudo apt-get install build-essential patch ruby-dev zlib1g-dev liblzma-dev

Missing script i18nliner-handlebars

Missing script i18nliner-handlebars Add this lines into your package.json file "handlebars": "~1",  "ember-template-compiler": "~1.8",  "i18nliner-handlebars": "~0.1",  "minimist": "~1.1" //ignore if your package.json already have this line