Posts

Showing posts with the label ruby

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

Setup ruby god for rails application || Daemons setup for rails application

 1) Install god on Ubuntu/Linux machine      sudo apt update      sudo apt install ruby-god 2) Create new rails application if you don't have existing 3) In your Gemfile add new gem       gem 'god', '~> 0.13.7', require: false 4) Then run bundle install 5) create a folder named daemons inside your  lib folder 6) create a file name daemons.god inside daemons folder (this file name or folder name can be anything its totally up to you) 7) Then paste this on you daemons.god file      ENV["RAILS_ENV"] = "development"      RAILS_ENV  = ENV.fetch('RAILS_ENV', 'production')      RAILS_ROOT = File.expand_path('../../..', __FILE__)      require 'shellwords'      # Create non-default log/daemons directory.      require 'fileutils'      FileUtils.mkdir_p "#{RAILS_ROOT}/log/daemons"      def daemon(name, options = {})        God.watch do |w|          command        = "bundle exec ruby lib/daemons/#{op

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

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

Download pdf by ajax or javascript or angular js

Click on button for generate pdf  $("#print_selected_label").on("click", function(){    data = []    $("input:checkbox.print_label:checked").each(function(){      data.push($(this).attr("id"));    });   //getting all information of checked checkbox    if(data.length > 0){    // if data is not null       In angular js controller         // var redirect_new = "/admin/v2/orders/print_multiple_label.pdf?" + jQuery.param(data);        // var pdf = window.open(redirect_new, 'Map PDF', '');      By Creating a link by javascript       // var mydiv = document.getElementById("download_pdf");      // var aTag = document.createElement('a');      // var link = " admin/v2/orders/print_multiple_label.pdf?id="+data ;      // aTag.setAttribute('href',link);      // aTag.innerHTML = "link text";      // mydiv.appendChild(aTag);      // aTag.click(); By making http request    

How to customise active admin page on keypress

Image
How to customise active admin page on keypress First make new route for getting filtered data: get '/admin/gyms/search_user', :to => 'admin/gyms#search_user', as: :search_gym_user In your controller create new method def search_user      @user =  User.where("name = ? AND role = ?", params[:name], "none") if params[:name].present?      respond_to do |format|        format.json  { render :json => @user }      end    end Render partial and add a id to to table panel "Gym Users:", :id => "foo-panel" do      # renders app/views/admin/posts/_search_users.html.erb       render 'search_users', { users: gym.users }      table_for gym.users, id: "search_gym_user" do        # binding.pry        # filter :"name" , :as => :select, :collection => gym.users.pluck(:name)        column "Joined" do |user|          distance_of_time_in_words(user.created_at, Time.now)    

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

If we are getting problem with FFMPEG || ffmpeg thumbnailer error in rails

If we are getting problem with FFMPEG  || ffmpeg thumbnailer error in rails Safely Remove FFMPEG First sudo apt-get --purge remove ffmpeg sudo apt-get --purge autoremove sudo apt-get install ppa-purge sudo ppa-purge ppa:jon-severinsson/ffmpeg sudo add-apt-repository ppa:mc3man/trusty-media sudo apt-get update sudo apt-get dist-upgrade sudo apt-get install ffmpeg And try if you still have problem then, apt-get update apt-get install build-essential git curl gawk useradd -m guest su guest cd export LOCAL_BREW_ENV="$HOME/my_graphviz" mkdir -p "$LOCAL_BREW_ENV" git clone https://github.com/Linuxbrew/brew.git "$LOCAL_BREW_ENV" export PATH="$LOCAL_BREW_ENV/bin:$LOCAL_BREW_ENV/sbin:$PATH" export MANPATH="$LOCAL_BREW_ENV/share/man:$MANPATH" export INFOPATH="$LOCAL_BREW_ENV/share/info:$INFOPATH" export HOMEBREW_CACHE="$LOCAL_BREW_ENV/var/cache" export HOMEBREW_LOGS="$LOCAL_BREW_ENV/va

An error occurred while installing rmagick (2.16.0), and Bundler cannot continue

An error occurred while installing rmagick (2.16.0), and Bundler cannot continue You have to install library of rmagick in your system. sudo apt-get install imagemagick libmagickcore-dev libmagickwand-dev

NoMethodError: undefined method `has_many?'

NoMethodError: undefined method `has_many?' In your gem file-  group :test do     gem 'capybara', '~> 2.1.0'     gem 'shoulda-matchers', '~> 3.0' end Run - bundle install in your spec_helper-  Shoulda::Matchers.configure do |config|   config.integrate do |with|     with.test_framework :rspec     with.library :rails   end end In to do TodoItem model require 'spec_helper' describe TodoItem do   it { should belong_to(:todo_list) } end In to do TodoList Model require 'spec_helper' describe TodoList do   it { should have_many(:todo_items) } end

Searching on Select Box and Check Box || List

Searching on Select Box and Check Box Searching on List <input type="text" id="myInput" onkeyup="filterFunction()" placeholder="Search.." > <ul id="myulli">   <li><a href="#">abc</a></li>   <li><a href="#">xyz</a></li>  <li><a href="#">demo</a></li> <li><a href="#">testing</a></li> </ul> <script> function filterFunction(){    var input, filter, ul, li, a, i;    input = document.getElementById("myInput");    filter = input.value.toUpperCase();    div = document.getElementById("myulli");    a = div.getElementsByTagName("li");    console.log(a);    for (i = 0; i < a.length; i++) {        if (a[i].innerHTML.toUpperCase().indexOf(filter) > -1) {            a[i].style.display = "";        }

Make admin panel with Active admin rails || active_admin rails

Image
Make admin panel with Active admin rails || active_admin rails  Open Terminal and copy and paste this Command rails new admin_example // creating new rails application go inside the project cd admin_example run bundle install bundle install open your gem file and add this new gem's gem 'activeadmin' / / for active admin panel gem 'inherited_resources' //  making your controllers inherit all restful actions gem 'devise' // for user authentication  run bundle install again bundle install install active admin rails g active_admin:install / /install active admin to your project migrate database rake db:migrate check your seed file and run rake db:seed create user file and model rails g User name email  create post file and model rails g Post title body:text published_at:datetime user:references Now Migrate DataBase rake db:migrate start rails server rails s Hit url localhost:3000/admin/login Enter login details you can find login

convert string value into fractional in ruby on rails

Convert string value into fractional self.try(:shipping).fractional.to_f   // this will convert string value to fractional example- if  self.try(:shipping)  =>   #<1500 Euro shiiping> then   self.try(:shipping).fractional.to_f will return 1500

How to locate nginx configuraion file on server

How to locate nginx configuraion file on server login to server on console  cd /etc/nginx/ sudo nano nginx.conf if does not locate cd /usr/local/nginx/conf/ sudo nano nginx.conf or try this too cd /usr/local/etc/nginx/ sudo nano nginx.conf

Difference Between pluck and collect

Difference Between pluck and collect Pluck Pluck takes less time then collect because when we use collect we have to execute two queries for collecting record Example-  When have a user table and we have to collect all id's User.all.collect(&:id) // when we use collect we are running two query internally                                        first user.all and then we collect id's User.pluck(:id) // Here we are running only one query that's why it take less time Pluck also take more than one parameter at a time but collect can not Example- user.pluck(:id, :name) // it will return array of id and name user.collect(&:id , &:name) // it will give an error