Pages

Monday, 16 November 2015

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.


Some ROR coding Standards

ROR Coding standards

Basic Stuff


 Two Spaces, No tabs

 Keep lines to a reasonable length(80 characters is classical but 100-120 is probably acceptable

with screen sizes these days)

 Method names should be intuitive and meaningful

 Variable names should be intuitive and meaningful

 Don’t commit commented out code - It makes everything confusing and it’s in the version

control anyway

 Comment when necessary - If comments are necessary check that your code couldn’t be

simplified first

 Maintain application style - If it’s a new application then be Railsy.

 If you want your application to survive then prioritize making the code easy to understand and

navigate.

Code style

 Use UTF-8. It’s 21 century, 8bit encodings dead now.

 Use 2 space indent, not tabs

 Use Unix-style line endings

 Keep lines not longer than 80 chars

 Remove trailing whitespace

Development process

 Think

 Describe

 Write tests

 Implement & go green

 Rethink

 Refactor

MVC


 Follow MVC conventions

 Do not ever mix logics: no model/view logic in controller, no view logic in model & etc.

 Follow “Fat model, skinny controllers” methodology

 If you have different data representation, use format aliases (e.g. different html views for same

data: /users/:id.iphone)

Controllers


 Keep it simple and clean

 Keep ApplicationController clean. Commonly it should be used only for global filters and per-

request logic (e.g locale configuration and access control)

 Keep in mind that all ApplicationController filters will be executed in each request and optimize

it to be ultra-fast

 Controllers should operate with abstract logic. Keep this logic simple and understandable

without detailed review. E.g:

# Disgusting


  Account.transaction do

    transfer = @sender.orders.new(:action => :transfer, :receiver => @receiver, :ammount)

   

    if @sender.assets >= amount

      @sender.assets -= amount

      @receiver.assets += amount

    else

      flash[:error] = "Balance not enough to transfer funds"

      success = false

    end

   

    if @sender.save! and @receiver.save! and transfer.save!

      flash[:info] = "You have transferred #{ammount} to #{@receiver.last_name + "" +

@receiver.first_name}"

      success = true

    else

      errors = ...

    end

  end

 

  if !success

    respond_to ...

  else

    respond_to ...

  end

# Much better, but not quite abstract


  Account.transaction do

    @sender.withdraw amount

    @receiver.deposit amount

  end

  if @sender.errors? or @receiver.errors?

    respond_to ...

  else

    respond_to ...

  end

# Best way

  if @sender.transfer!(amount, :to => @receiver)

    respond_to ...

  else

    respond_to

  end

 View interaction in controllers always should be placed in respond_to method or in responders

(for Rails 3)

 Do not place any logic in respond_to method

 Prefer :except in filters. E.g.: before_filter :authorize!, :except => [:index] to be sure that new

actions will be covered by filter by default

 Follow REST convention: Commonly one controller should only operate one resource.

 Follow REST convention naming. E.g.: UsersController should operate only users. Groups

operations should be placed in GroupsController

 Follow HTTP methods conventions in REST actions: DELETE for destructive action, PUT for

update, POST to create, GET to read

 Use nested resources when needed. E.g: map.resource :users {|user| user.resource :groups

}instead of groups action in UsersController

 Avoid deep nesting where it’s not necessary. E.g:

Not /places/:place_id/events/:event_id/usersbut /events/:event_id/users

Models


 Keep it simple and clean

 Model, method and variable names should be obvious

 Do not use shortcuts and avoid non widely used abbreviation for model names. (e.g UsrHst or

UserHist should be UserHistory)

 Don’t repeat yourself

 Don’t repeat rails. Zero custom code that duplicates rails built-in functionality

 If you use find with similar condition in more than once — use named_scope

 If you use same code in more than one model turn it into module/library

 Prefer XML Builder over to_xml overrides

Views

 Views is for presentation. DO NOT EVER CHANGE STATE OF ANYTHING IN VIEW

 Keep views simple

 Move complex logic to helpers

 Move HTML markup generation to helpers

 Do not use finders in views

 DRY. Use partials, but keep in mind that partials can be really slow

 Keep HTML markup semantic an clean

 Do not inline any Javascript code. It should be unobtrusive

Tests

 Follow Test Driven Development methodology: write tests, then code

 Keep tests simple and easy understandable

 Test everything what should be tested. If something can be broken: try to broke it by test

 Do not test rails built-in methods, test method usage


For more updates please fork on github

https://github.com/tarungarg/rails-style-guide

collection_check_boxes Rails Example

HTML code
<div style="width: 150px;height: 100px;overflow: scroll;">
 <%= check_box_tag "All" %>All<br/>   
 <%= f.collection_check_boxes  :category_ids, Category.all, :id, :category_name do |b| %>
    <span>
    <%= b.check_box(class: "check_box")%>
    <%= b.label %>
    </span>
 <% end %>
</div>
Javascript Code 
<script type="text/javascript">
  $(document).ready(function(){
    $('#All').click(function() {  
        if (this.checked) {
           $('.check_box').each(function() {
              this.checked = true;                       
           });
        } else {
           $('.checkbox').each(function() {
              this.checked = false;                       
           });
        }  
     });
   });
</script>