Posts

Showing posts with the label rails server

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

Data Scrapping in rails

go to your terminal create a directory mkdir ruby_data_scrapping create directory mkdir lib cd lib/ touch scraper.rb gem install nokogiri  // install gems in local gem install httparty gem install byebug Write code in your scraper.rb require "httparty" require "nokogiri" require "byebug" class Scraper   attr_accessor :parse_page   def initialize       doc = HTTParty.get("https://in.tradingview.com/markets/currencies/rates-africa/")       @parse_page ||= Nokogiri::HTML(doc)   end   def get_prices      item_container.first(2).last.children.map{|x| x.text}   end   private     def item_container        parse_page.css(".tv-data-table__tbody").first.css(".tv-screener-table__result-row").css(".tv-screener-table__cell")     end   prices = Scraper.new.get_prices   (0...prices.size).each do |index|       puts "Price: #{prices[index]}"   end end now run this scraper ruby scraper.rb

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

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 

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    

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

how to run rake task from console

how to run rake task from console In your file_name.rake namespace rake_task   namespace first_rake     task task_first do       // some code     end     task task_second do        // some code     end   end end Now run this task rake rake_task:first_rake:task_first

Uploading Images With Carrierwave to S3 on Rails

Uploading Images With Carrierwave to S3 on Rails In your gem file gem 'carrierwave', '0.10.0' gem "mini_magick" gem "fog" Run bundle install In app/models/Your_model_name.rb   mount_uploader :your_field_name, ImageUploader app/uploaders/image_uploader.rb class ImageUploader < CarrierWave::Uploader::Base     include CarrierWave::MiniMagick     storage :fog     def store_dir     "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"   end     version :large do     process resize_to_limit: [800, 800]   end     version :medium, :from_version => :large do     process resize_to_limit: [500, 500]   end     version :thumb, :from_version => :medium do     process resize_to_fit: [100, 100]   end     version :square do     process :resize_to_fill => [500, 500]   end   end Create a file in ditectory config/initializers/s3.rb CarrierWave.co