Pages

Monday, 16 November 2015

Understanding on Singleton

Code for singleton pattern

require "singleton"

class SimpleLogger
  include Singleton

  def initialize
    @output = []
  end

  attr_reader :output

  def error(message)
    output << formatted_message(message, "ERROR")
  end

  def info(message)
    output << formatted_message(message, "INFO")
  end

  def write(filename)
    File.open(filename, "a") { |f| f << output.join }
  end

  private

  def formatted_message(message, message_type)
    "#{Time.now} | #{message_type}: #{message}\n"
  end
end

Upgradation rails 2 to rails 4 (Errors)

Some Errors are given below while migration of rails 2 to rails 4
  • 'rake/rdoctask' is obsolete and no longer supported. Use 'rdoc/task' (available in RDoc 2.4.2+) instead.
require 'rake/rdoctask'
to
require 'rdoc/task'
  • undefined method `attr_accessible' for
Add ‘gem 'protected_attributes' to Gemfile
  • undefined method `link_to_function' for
Add patch in app/helpers/link_to_helper_function.rb

module LinkToFunctionHelper def link_to_function(name, *args, &block) html_options = args.extract_options!.symbolize_keys function = block_given? ? update_page(&block) : args[0] || '' onclick = "#{"#{html_options[:onclick]}; " if html_options[:onclick]}#{function}; return false;" href = html_options[:href] || '#' content_tag(:a, name, html_options.merge(:href => href, :onclick => onclick)) end end
  • ActiveRecord::AssociationNotFoundError (Association named 'authorizations' was not found on User
Change in lib/authenticated_system.rb:108 to (if using restful-authentication)


User.includes(:roles => :authorizations).find_by_id(session[:user_id])

  • undefined method `has_strings' for
Comment has_string wherever you find it.

  • Unknown key: :order. Valid keys are: :class_name, :class, :foreign_key…
Change format something like that


has_many :commission_reports, :order => "volume_year DESC, volume_month DESC", :dependent => :destroytohas_many :commission_reports, -> { order "volume_year DESC, volume_month DESC" }, dependent: :destroy
  • undefined method `on' for #<ActiveModel::Errors
Rails 4, the problem is that there's no "on" method for the Errors class anymore. We use "get". From

Change format something like that
@user.contact.errors.on(:attended_before)
 to
@user.contact.errors.get(:attended_before)
  • undefined method `call' when doing a simple query
Change scope from all models from

scope :enquiry, where({:involvement => INVOLVEMENT_ENQUIRY, :archived => false})
to
scope :enquiry, -> { where({:involvement => INVOLVEMENT_ENQUIRY, :archived => false}) }
  • Fix Typical Syntax on has_many like associations 
has_many :prices, -> { includes(:country).order("created_at desc") }, as: :priceable, dependent: :destroy, class_name: "Price"
  • Undefined method confirmed_me?
remove :confirmable from model where we have defined the devise parameters eg User model if not using
  • Unknown key: :include
Change has_many statement


  • NoMethodError (undefined method `authenticated?' )

FInd authenticated?  and replace with devise method valid_password?

  • NoMethodError (undefined method `forget_me' for
Copy forget_me method from restful-authentication to User model
  • link_to_function and the view helper with postfix _tag doesn’t work in rails 4 so the solution is
Add  Gem  into the gem file
gem 'prototype-rails'
In rails 2 prototype was supported but in rails 3 the jquery supports so we get the errors like
  • Keep in mind that the rails 2 already create a application.js and application.css in public folder so do not create same name files in assets folder. That can also give you conflicts.
  • element.dispatchEvent is not a function
Go to layout and check application layout


Here you have include the app/assets and public/assets together

So keep in mind the hierarchy of inclusion of files, in short
first jquery
second prototype
referred link
http://learn.jquery.com/using-jquery-core/avoid-conflicts-other-libraries/

<script src="prototype.js"></script>
<script src="jquery.js"></script>

After that include below in head of the html file the below line
<script>jQuery.noConflict();</script>
  • javascript_include_tag :default doesn’t work in rails 4
  • calendar_date_select doesn’t work in rails 4
  • LocalJump Error
This is due to the return keyword written in block. So remove return from the block.
  • undefined method `scoped' for
scoped method has been deprecated from rails 4. use all on place of it.
  • Search Or.. functionality was not working so change it that code
Replace div with some some id
  • Move all the assets from public folder to app folder



restful_authentication to Devise Migration


  • Add the following gem into your Gemfile
    • gem 'devise'
    • gem 'devise-encryptable'
  • Run the following commands from console
    • bundle intstall
    • rails g devise:install
  • In model file whatever you are using saving user information like user.rb
    • devise :database_authenticatable, :registerable, :recoverable, :rememberable, :confirmable, :validatable, :encryptable, :encryptor => :restful_authentication_sha1
          Modules :encryptable and :encryptor => :restful_authentication_sha1 are important here.
  • In config/initializers/devise.rb, configure as below
config.stretches = 1 config.pepper = ""

We are setting empty pepper and stretches to 1. This is how restful authentication works. It does not use stretches or pepper (by default).

( Note: You may find REST_AUTH_SITE_KEY in config/initializers/site_keys.rb )

In other case if You did set the REST_AUTH_SITE_KEY , then configure as below
config.stretches = 10
  config.pepper = "<YOUR_REST_AUTH_SITE_KEY>"

  • If you're using :validatable you may have to adjust your minimum password length. Devise uses 8, restful_authentication uses 6.
  • In config/initializers/devise.rb
                    config.password_length = 6..128

That is it for configuration. Now we have to change the table column names (without deleting them) to give devise what it wants. Here is the migration file I used. Change it according to your app's business logic.
  • Add migration to change columns
class ConvertRaToDevise < ActiveRecord::Migration
def self.up
  rename_column :users, "crypted_password", "encrypted_password"
 change_column :users, "encrypted_password", :string, :limit => 128, :default => "", :null => false
  rename_column :users, "salt", "password_salt"
  change_column :users, "password_salt", :string, :default => "", :null => false
  add_column :users, "remember_created_at", :datetime
end

def self.down
  remove_column :users, "remember_created_at"
  rename_column :users, "encrypted_password", "crypted_password"
  change_column :users, "crypted_password", :string, :limit => 40
  rename_column :users, "password_salt", "salt"
  change_column :users, "salt", :string, :limit => 40
end
end

You will able to use devise as authentication for your project.

Rails 2 to 4 UpGradation (Initial Level Settings)

Steps to upgrade the rails from 2 to 4 (Initial Level Settings)

  • Use latest ruby version first which is compatible with rails 4
  • Upgrade your Gems
    • Change versions for Gems into Gemfile .
    • Find alternative for gems which have been deprecated.
    • Comment some below gems if you have into you Gemfile
      • gem "mongrel"
      • gem "cgi_multipart_eof_fix" 
      • gem "fastercsv", '1.5.0'
      • gem “debugger"
    • Remove versions for these two basic Gems
      • gem 'mysql2'
      • gem 'rake'
  • Comment all the mime initializers in file config/initializers/mime_types.rb
  • Add config.egger_load in all rails environments in files config/environments/*
    • config.eager_load = true
  • Change match keyword from file routes.rb to get

You will able to run rails server from console

Wednesday, 30 September 2015

About Me

About Me

My name is Tarun Garg, I’m 25 year old Software Engineer.  As I spend my work days working with an organisation. I have 4 years of relative experience in rails I live in Delhi, India. My total experience includes website development in ruby on rails. I also like to work as a freelancer for extra pays. 
I have in-depth knowledge and experience in requirement gathering, analysis, design, development, testing, API designs, AWS technologies and implementation of methodologies. I also offers experience in preparing standard documents such as program specification, design document, and training document. I am proficient in understanding business processes and requirements, and translating them into functional specifications. I have ability to build world class products using Agile/Scrum.
My responsibilities as Software developer includes client handling, better code optimizations, client satisfactions, understand requirements, better listener and give best to client. I assisted in the successful completion of some projects based on ROR. My clients also relied on my ability to skills such as code optimization, task completion, meet client requirements and excellent communications skills.

Thursday, 29 January 2015

Bind Ports in UBUNTU

We always get the below errors on ubuntu machine in some cases

(98)Address already in use: AH00072: make_sock: could not bind to address [::]:80
(98)Address already in use: AH00072: make_sock: could not bind to address 0.0.0.0:80


I find the a command better than other commands to check binding of port 80 or some other port

command: 
$ sudo netstat -tulpn | grep :80

Result:
tcp        0      0 127.0.0.1:80            0.0.0.0:*       LISTEN      152/aolserver4-nsd


To kill the process

$ killall aolserver4-nsd


Now our port 80 is free to use

Log Rotation In Rails in Ubuntu

When we set up our application on server, we forget to rotate our logs.
What the rotate means here?
if your log size is increasing from some given value than the log will be replaced with a new empty file.
What is use of it?
If we do not rotate our logs, it takes a lot of memory and reach in GBs. It take a lot of useful space and server speed gets slow down after some time. It is junk and need to be clean after some time.
How we can do it?
There are two way to do so
one is set cron and second is there is a logrotate directory in linux so follow the below steps to rotate logs.

  1. In Linux, run the below command in terminal
        cd /etc/logrotate.d

  1. Create a new file, Write below command
        touch hc                    (hc is rails application name, it can be any name)

  1. Run the following commands and fill the file with below lines.
   
    sudo vi hc

    copy and paste the below lines

/home/likewise-open/ICPL/tarun.garg/apps/holidaycomparisons/log/*.log {
   size=20M
   daily
   rotate 3
   compress
   delaycompress
   missingok
   notifempty
   create 644 tarun.garg domain^users
}

/home/likewise-open/ICPL/tarun.garg/apps/holidaycomparisons/log/*.log  is path to my log directory

  1. 'rotate 3' signifies that only 3 logs of particular file.
  2. logfiles can be compressed using the gzip format by specifying 'compress' and 'delaycompress' delays the compression process till the next log rotation. 'delaycompress' will work only if 'compress' option is specified.
  3. 'missingok' avoids halting on any error and carries on with the next log file.
  4. 'notifempty' avoid log rotation if the logfile is empty.
  5. 'create <mode> <owner> <group>' creates a new empty file with the specified properties after log-rotation.
  6. Daily signifies that check the log daily.
  7. size signifies the size of the log after which it should be compressed.