Ruby Conditional Assigment Operator ||=

May 5th, 2010

Conditional Assignment Operator, ||=, allows you to set the value of a variable, if there is no previous value set to it. This is a shorthand for something like this:

def get_instance
  unless @car
    @car = Car.new
  end
end 

This code can be shorthand to :

def get_instance
    @car = @car || Car.new
end 

You can even further shorthand the method to:

def get_instance
    @car ||= Car.new
end 
Author: Abdul Basit Munda Categories: Uncategorized Tags:

Aliasing a Method

May 1st, 2010

In Ruby, aliasing a method is a very cool way of overriding a method, but still having the ability to call the original, overrided method. For example:

if you have a global filter defined in the ApplicationController called authenticate :

class ApplicationController < ActionController::Base
  before_filter :authenticate;
  def autenticate
     authenticate_user();
  end
end

and you wanted to make a small change to that authenticate filter for the HelloController, we can use an alias_method(new_name, old_name) to achieve that:

class HelloController < ApplicationController
   alias_method orig_authenticate, authenticate
  def authenticate
     do_some_extra_stuff();
     # Call original authenticate method
     orig_authenticate();
  end
end

This is very useful in occasions, where you would like to override a method, but still want to access the overridden methods.

Author: Abdul Basit Munda Categories: Uncategorized Tags:

Changing the Table Name Convention

April 20th, 2010

Rails has a convention of making the table names plural, and a model names singular. For example, if a model name is Order then database table name will be Orders.

This convention is great most of the time but what about if you have a legacy database table and you wanted to port the application onto Rails. Fortunately, there is a solution. You can easily change this convention, by setting set_table_name table name in the model.

For Example:
class Order < ActiveRecord::Base
set_table_name "legacy_order"
end

Author: Abdul Basit Munda Categories: Uncategorized Tags:

Riding Rails

January 29th, 2010

I decided to relearn Rails, last time I touched Rails was two years ago for my software engineering course. Since then I always wanted to dig deeper into Rails but time was always against me.

I will be using this blog to convey my learning, observations and comparisons with Rails and other technologies I have learned over the years. So lets start!

puts rails_learning

Author: Abdul Basit Munda Categories: General Tags: