Posts

Showing posts with the label rubyonrails

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

Transition Block in Rails with_lock

What is with_lock? how it work Ans:  If two users read a value from a record and then update it simultaneously, one of the values has to “win” and data integrity will be compromised. This is dangerous especially when dealing with money or inventory stocks. For example: User has a card balance = 10 User opens browser A and fill out 5 USD to buy User opens browser B and fill out 10 USD to buy User hits “Buy” button of both browsers at the same time Request A reads card balance=10 Request B reads card balance=10 Request A updates balance -= 5 (balance now is 10-5=5) Request B still has the instance card balance=10 (even though request A already decremented it) Request B updates balance -= 10 (balance now is 10-10=0) Final balance is now 0 User was able to purchase 15 USD when the initial balance was only 10 USD. This is race condition potentially at its worst case! Rails doesn’t do locking when loading a row from the database by default. If the same row of data from a table is loaded by t

Faraday::SSLError: SSL_connect returned=1 errno=0 state=error: certificate verify failed (certificate has expired)

  require 'openssl' OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE put this lines in config/application.rb

Some Ruby on Rails interview questions

 1) How flash message work in ruby on rails? Ans. They are stored in your session store. The default since rails 2.0 is the cookie store, but check in config/initializers/session_store.rb to check if you're using something other than the default. According to APIdock : ActionController/Flash, it is stored in a session. Note that if sessions are disabled only flash.now will work. When using flash.now, your values are not available in the next request. 2) What is the use of Asset-PipeLine in Rails? Ans. Assets(css, scss, js, coffeescript, images etc), its fast executed in rails application because of asset pipeline when we compile it or when its compiled, it will generate a single source code file or a manifest file, so that's why assets are interpret fastly. 3)   Difference between find and find_by? Ans . The find method is usually used to retrieve a row by ID:            Model.find(1)           And it will throw ActiveRecord::RecordNotFound error if record not found. find_by is

Some important and unknown(least used) ruby methods.

 1) inject or reduce      When called, the inject method will pass each element and accumulate each sequentially.     ex:         [1,2,3].inject(:+)    => ((1+2)+3))   //we have can any operator here i.e +,-,*,/,%         OR         [1,2,3].inject{|sum, value| sum + value } => 1 iteration:  (1 + 2)                                                                                             =>  2 iteration: (3(1st iteration sum)+3)            we  can also pass it a default value or base value for the accumulator.     ex:          [1,2,3].inject(0, :+)    => (0+(1+2)+3)) //so here initial value for sum is 0.          We can also use inject menthods for building hash's from the array's     ex:           [[:book, "data structure"], [:price, "400rs"]].inject({}) do |result, element|               result[element.first] = element.last               result           end            #=> {:book=>"data structure", :price=>"400rs&qu

rails redirect after login devise

devise_scope :user do  authenticated :user do    root 'dashboard#index', as: :authenticated_root  end  unauthenticated do    root 'home#index', as: :unauthenticated_root  end end

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' }

some minor things in rails

For Date format  .utc.strftime('%d-%m-%Y %H:%M:%S') Alternative to html_safe (raw("<strong class='text-danger'>Decline</strong")). select tag for form_for  <%= f.select(:currency_id, options_for_select(@currencies.map{|x| x.id}, f.object.payment_currency), {include_blank: "Select Currency"}, { :class => 'form-control', required: true }) %> zip -r new_file_name.zip folder_name

Convert numbers in rails like binary to decimal

value.to_i(from).to_s(to) i.e "1000".to_i(2).to_s(10) //here we are converting binary to decimal

decimal to binary converter in rails

def dec2bin(number)     number = Integer(number) //number that you have to convert     if(number == 0) then 0 end              new_num = ""     while(number != 0)         new_num = String(number % 2) + new_num         number = number / 2     end     new_num // return new number end

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!   

Wicked-PDF not showing images, 'wicked_pdf_image_tag' undefined

Wicked-PDF not showing images, 'wicked_pdf_image_tag' undefined <div>   <%= wicked_pdf_image_tag 'logo.jpg' %> </div> def save   pdf = WickedPdf.new.pdf_from_string(                         render_to_string(                           template: 'example/pdf_view.pdf.erb',                           layout: 'layouts/application.pdf.erb'))   send_data(pdf,             filename: 'file_name.pdf',             type: 'application/pdf',             disposition: 'attachment')  end 

How to override method in rails 5 plugin

Override controller method in our plugin rails 5 Here i override user controller method in this plugin you can review this plugin cilck here to download plugin