Pages

Monday, December 30, 2013

Blocks in Ruby

Ruby has a concept of Block.
  • A block consists of chunks of code.
  • You assign a name to a block.
  • The code in the block is always enclosed within braces ({}).
  • A block is always invoked from a function with the same name as that of the block. This means that if you have a block with the name test, then you use the function test to invoke this block.
  • You invoke a block by using the yield statement.

Syntax:

block_name{
   statement1
   statement2
   ..........
}
Here, you will learn to invoke a block by using a simple yield statement. You will also learn to use ayield statement with parameters for invoking a block. You will check the sample code with both types ofyield statements.

Single Table Inheritance(STI) in Rails 3

What is Single Table Inheritance?
In a nutshell, STI allows you to create sub-classes of a particular database table. Using a single table, you can cast rows to specific objects that extend the base model.
How to create STI relationships in Rails
Lets say we have a model Computer
 class Computer < ActiveRecord:Base
  # in app/models
  # Fields:
  #   String name
  #   String owner
  #   String manafacturer
  #   String color

  def default_browser
    "unknown!"
  end 
end

Friday, December 27, 2013

Access of Current Login user in Model

In  your model put the following code what ever the model is let suppose model is User then.


class User < ActiveRecord::Base
  def self.current
    Thread.current[:user]
  end
  def self.current=(user)
    Thread.current[:user] = user
  end
end

After this now in your application controller do like this.
class ApplicationController < ActionController::Base
    def set_current_user
      User.current = current_user
    end
end
class ApplicationController < ActionController::Base
   before_filter :set_current_user
end
Now you can easily fetch the current_user in models by User.current

ORM for Rails

ActiveRecord: Object-Relational Mapping(ORM) for Rails


  • Object Relational Mapping (ORM): simplify the use of databases in applications.
    • Use objects to hold database records
      • One class for each table in the database
      • Objects of the class correspond to rows in the table
      • Attributes of an object correspond to columns from the row
    • Manage the movement of information between objects and the back-end database.
    • Manage relationships between tables (joins), turn into linked data structures.

Always add DB index

Always add index for foreign key, columns that need to be sorted, lookup fields and columns that are used in a GROUP BY. This can improve the performance for sql query. If you're not sure which column need to index , I recommend to use https://github.com/fgrehm/lol_dba, which provide rake tasks to find missing indexes.

Bad Smell

class CreateComments < ActiveRecord::Migration
  def self.up
    create_table "comments" do |t|
      t.string :content
      t.integer :post_id
      t.integer :user_id
    end
  end

  def self.down
    drop_table "comments"
  end
end
By default, rails does not add indexes automatically for foreign key, you should add indexes by yourself.

Thursday, December 26, 2013

Counter Cache in Rails - Performance Tuning

If you need to display the record count for a has_many association, you can improve performance by caching that number in a column.
Below we have an application that shows a list of projects along with the number of tasks that each project has.

Wednesday, December 25, 2013

Is Ruby on Rails is right choice for your new website?

Ruby on Rails (often referred to as just "Rails") is a framework for building websites that can make it more affordable to create and maintain your site, while simultaneously offering improved performance and faster development times.

Below are some guidelines for determining whether Ruby on Rails would be a good choice for your project.

The benefits of Ruby on Rails
Overall, as a business owner, the three largest benefits you can expect with Ruby on Rails are:
  • QUICKER LAUNCH. Sites that would traditionally take 12 weeks to build can commonly be launched inside of 6 weeks with Ruby on Rails. This time savings results from a few factors: a leaner code-base (fewer lines of redundant code), a modular design (re-using existing components rather than building everything from scratch), and the availability of existing plugins (again, reducing the need to build features from scratch).
  • EASIER CHANGES. After site launch, future modifications to your site (e.g., adding new features, making changes to the data model) can be made more quickly, for the same reasons noted above.
  • MORE COST-EFFECTIVE. Because of the speed with which Rails sites can be built and modified, you spend less money to create and maintain the website — without compromising the quality, performance, or scalability of your site.

Tuesday, December 24, 2013

Convention over Configuration in Rails

Rails promotes "convention over configuration". Default rendering is an excellent example of this. By default, controllers in Rails automatically render views with names that correspond to valid routes. For example, if you have this code in your BooksController class:
class BooksController < ApplicationController
end
And the following in your routes file:
resources :books

And you have a view file app/views/books/index.html.erb:
<h1>Books are coming soon!</h1>
Rails will automatically render app/views/books/index.html.erb when you navigate to /booksand you will see "Books are coming soon!" on your screen.

Top Web Application Security Problems

How to secure a Web application to avoid hacking? Here are the top most common security risks for a web application that a developer should be awared of.
1.  Cross-site Scripting
Social network and public forum application usually re-post a user post to other readers. When the application display a user post without sanitize the data, a hacker can enter harmful JavaScript in the page.  The JavaScript code will be executed when readers read the page.  The script can steal a user session cookies, redirect a user to a look-a-like-site, or stealing data etc ... Always sanitize user entered data and reject the request for suspicious text.
2.  Session fixation
A hacker obtains a valid session cookie for a particular web site by visiting a web page in the site .  The hacker may post a JavaScript in the web site which replace a visitor cookie with this new session cookie.  When a user view the infested page, the session cookie will be therefore replaced.  The user may be fooled to login again which the hacker can access the account from another machine using the same session cookie.  Web developer needs to sanitize a user post to strip out JavaScript before re-display the text. 

Monday, December 23, 2013

Best way to transfer db from one heroku app to another

It's quite common to migrate databases between staging, testing and production environments for Rails Apps. And heroku db:pull/push is painfully slow. The best way I have found so far is using Heroku PG Backups add-on and it's free. I followed following steps to migrate production database to staging server:
1) add pgbackups add-on to production and staging apps
heroku addons:add pgbackups:basic --app production-app
heroku addons:add pgbackups:basic --app staging-app
Since I am only using pgbackups for migration, basic plan is enough for this.

14 Bare Minimum Security Checks Before Releasing a Rails App

When you upload your latest app to a production Web server and open it up to the world, you're really throwing your app to the elements - good and bad. If you don't pay any attention to security whatsoever, you're likely to fall foul of some cracker's nefarious scheme and your users will be complaining when something doesn't work or they're being spammed by geriatric Nigerian clowns with pots of gold to share. But what to do?
Luckily, help is at hand in the shape of the official Ruby on Rails Security Guide, but Irish Rails developer Matthew Hutchinson has trawled through that guide as well as several illuminating blog posts relating to Rails security, and put together a 14 step checklist of "bare minimum" security checks to do before releasing your Rails app.
In summary:
  1. Don't trust logged in users. (Authentication is one thing, authorization to perform certain tasks is another.)
  2. Beware of mass assignments. (Use attr_accessible in your models!)

Sunday, December 22, 2013

How to Change Default Port i.e 3000 in Rails

Append these code lines in config/boot.rb:
require'rails/commands/server'
module Rails
  class Server
    alias:default_options_alias :default_options
    def default_options
      default_options_alias.merge!(:Port=>3333)
    end
  end
end
Now default port is 3333.
Set this number to any number with 4 digits that you like!!!

Saturday, December 21, 2013

Use Belongs_to With Presence Validator

Assume we have two models: User and Image. User has one image and image belongs to user. The code below:
class User < ActiveRecord::Base
  has_one :image
end

class Image < ActiveRecord::Base
  belongs_to :user
end
Now we want to add validation for image to check if user is there or not.
class Image < ActiveRecord::Base
  belongs_to :user
  validates :user, :presence => true
end
So by adding just one line whenever you are trying to save image object, it will fire a query with respect to the user_id to check weather that user exists or not. In case user doesn’t exits “image.save” with return an error.

Friday, December 20, 2013

How to Optimize Image Uploaded via Paperclip

Here is an another gem to reduce the size of the paperclip uploaded image.
    gem "paperclip-compression","~> 0.1.1"

Usage

    class User < ActiveRecord::Base
             has_attached_file :avatar,
              :styles     => { :medium => "300x300>", :thumb => "100x100>" },
              :processors => [:thumbnail, :compression]
    end
we can optimize this code as:

Boot your Rails development server and console faster than ever.... Use Zeus

How Zeus works?

Zeus preloads your Rails app so that your normal development tasks such as consoleserver,generate, and specs/tests take less than one second.

Install
Install the gem.
gem install zeus

Thursday, October 17, 2013

Difference b/w Rails 2 and Rails 3

Now a days Rails 3.2 version is going on. I am going to write some difference between in Rails 2.x and 3.x.

1. Some command line syntax has been changed in Rails 3.x like as
  •  rails generate instead of rails script/generate
  •  rails server instead of ruby server
 2. Introduction of bundler (New way to manage your gem dependencies)
       - Rails 3.x has bundle concept (Gem File) while Rails 2.x does not have

New features in Rails 4

Introduction:
Finally, the most awaited Rails 4.0 version has been released by the Rails team on 25th of June. Rails 4 has got huge changes. There are tons of new features available, which can make your life as a Rails developer a lot easier.  We will talk about the most exciting features in Rails 4 and why you should upgrade from Rails 3 version as soon as possible.
New features of Rails4
 1.  Ruby Versions
It is essential to note that Rails 4 would require Ruby 1.9.3 or higher, in fact Ruby 2.0.0 is recommended for your Rails 4 apps.

Observers in Rails 3

Rails observers are sweet, You can observe multiple models within a single observer
First, you need to generate your observer:

rails g observer Auditor

Then, in your fresh auditor_observer.rb file define the models you wish to observe and then add theafter_create callback.

class AuditorObserver < ActiveRecord::Observer
   observe :model_foo, :model_bar, :model_baz

   def after_create(record)
    #do something with `record`
   end
end



Wednesday, September 25, 2013

proc and lambda

proc and lambda in Ruby – Introduction

Today we are going to talk a little bit about the infamous procs and lambdas in Ruby and the differences between them. Well, you may already know that a proc and a lambda are objects of the same class:
  1. p, l = proc{}, lambda{}
  2. p.class
  3. #=> Proc
  4. l.class
  5. #=> Proc

So is proc an alias for lambda ? The answer is no. The Proc object returned by a call to proc{} has differences from the Proc object that the lambda{} call returns (This is only true for Ruby 1.9, as of Ruby 1.8 the proc and lambda was just aliases. In Ruby 1.8 the Proc object returned by a call to Proc.new was different from lambda).

Monday, May 20, 2013

The difference between require, load, Include and Extend

Here are the differences between Include, Load,Require and Extend methods in Ruby : 

--> Include: 

When you Include a module into your class as shown below, it’s as if you took the code defined within the module and inserted it within the class, where you ‘include’ it. It allows the ‘mixin’ behavior. It’s used to DRY up your code to avoid duplication, for instance, if there were multiple classes that would need the same code within the module. 

The following assumes that the module Log and class TestClass are defined in the same .rb file. If they were in separate files, then ‘load’ or ‘require’ must be used to let the class know about the module you’ve defined. 


module Log 
def class_type 
"This class is of type: #{self.class}" 
end 
end 

class TestClass 
include Log 
# ... 
end 

tc = TestClass.new.class_type 

The above will print “This class is of type: TestClass”