Make your Rails Code Better using “Metric_fu”

Metric_fu is a set of rake tasks and compilation of several different tools that provide reports that show which parts of your code might need extra work . It uses Saikuro, Flog, Flay, Rcov, Reek, Roodi, Subversion, Git, and Rails built-in stats task to create a series of reports.

Rcov – Measures test coverage
Flog – Measures code complexity
Saikuro – Measures cyclomatic complexity
Flay – Finds duplication (both copy/paste and structural)
Reek – Spots code smells
Roodi – Finds lots of general problems
Churn – Identifies files that change too often
Rails best practices– Code matric tool
Cane– Code quality threshold violations
HotSpot– Meta analysis of your metrics to find hotspots in the code


Add the gem in your gem file

gem “metric_fu”

Then run “bundle install”

Metric_fu will install several other dependencies unless they are already present. These include Flay, Flog, Rcov, Reek, Facets and Roodi. These are the tools that Metric_fu uses to generate its reports

Then, run the following command for generating the metrics

rake metrics:all

It will generate a matrics of your code in the temp/matric_fu folder, it uses a bunch of open source project to give all this to you


  • You can major the complexity
  • Creates a “hit list” of your most complex method
  • It helps you to prioritize
  • Make you reveal on unknown problems like bugs and hidden complexity
  • Examine the worst offenders
  • Refactoring complex methods yields many benefits like Smaller, easier to understand methods and Finding bugs


  • We are aware of unknown complexity
  • Our code will get worse if it is not getting better


Code analysis isn’t an exact science and none of the tools shown are perfect in themselves, so they should all be used as an aid to help you find the areas of your code that might need some work not as an absolute instruction that you must refactor a part of your application.Image



Twitter Bootstrap for Rails 3

Bootstrap is a toolkit from Twitter designed to kickstart development of webapps and sites. It includes base CSS and HTML for typography, forms, buttons, tables, grids, navigation, and more


Add gems inside asset group in your Gemfile

group :assets do
    gem ‘therubyracer’, ‘0.10.2’, :platforms => :ruby
    gem ‘libv8’, ‘’
    gem ‘less-rails’

    gem ‘twitter-bootstrap-rails’


bundle install


rails generate bootstrap:install less

Step – 4

Generating layouts and views

rails g bootstrap:layout [LAYOUT_NAME] [*fixed or fluid]

rails g bootstrap:layout application fluid


To add theme in all files of a resource (generates Twitter Bootstrap compatible scaffold views.)

rails g bootstrap:themed [RESOURCE_NAME]



rails g scaffold Post title:string description:text
rake db:migrate
rails g bootstrap:themed Posts



‘rails’ is not recognized as an internal or external command

This message means that Rails cannot be found. This might be due to the fact that you haven’t installed Rails or it may be due to the fact that the path to Rails cannot be found.

This might be the conflict of ruby of ruby path not set properly

Uninstall and Re-Install the ruby

Remove all version of rails

Then, run the gem from the system prompt, you should enter:

gem install rails –include-dependencies

Alternatively, you can download and install rails from the Ruby On Rails web site:

To make sure that Rails is installed, go to the system prompt and enter:


Customize the event calendar for holiday, halfday and fullday

Event calendar is a way to show multiple, overlapping events across calendar days and rows. This is an interface to add events, edit events, & destroy event.

I just cramped while implemented the halfday and fullday functionality in event caledar. I think it will help you.

Generate the JSON for the holiday, event day count and event status(half or full)

below are the snippets of code of controller

def index
	if request.xhr?
		@events = Event.order("created_at desc")
		events = []  
		holiday = []
	   @holiday = HolidayList.all
		@events.each do |event|
		  events << {:id =>, :title => + "   ( " + event.event_type.option + " )     "  ,:day_count => (event.days/0.5).to_s , :half=> ((event.days % 1) != 0) ? 1 : 0, :tip => "Type:" + event.event_type.option + " Resson:" +  event.reason || "",  :color=> event.event_type.color, :className=>"test",:description => event.reason || "Some cool description here...", :start => "#{event.from_date.iso8601}", :end => "#{event.to_date.iso8601}"}
		@holiday.each do |hol|
		  events << {:id =>, :title => + "   ( HOLIDAY )", :day_count => 1 ,:tip => "Type:Holiday  Resson:" + || "", :half=> 0, :color=> "#B6B6B6", :className=>"holi_day",:description => hol.description || "Some cool description here...", :start => "#{hol.h_date.iso8601}", :end => "#{hol.h_date.iso8601}"}
	  params[:for_year]"%Y") unless params[:for_year]
		events = Event.where("YEAR(from_date)=?",params[:for_year]).order("created_at desc")
    respond_to do |format|
	   format.xml  { render :xml => events }
      format.json { render json: events}

it will return the json data as below

	created_at: "2013-10-24T06:32:50Z",
	days: 1,
	from_date: "2013-10-26T00:00:00Z",
	id: 6,
	event_type_id: 3,
	reason: "Event",
	to_date: "2013-10-26T00:00:00Z",
	updated_at: "2013-10-24T06:32:50Z",
	user_id: 11
	created_at: "2013-10-24T06:32:14Z",
	days: 1.5,
	from_date: "2013-10-28T00:00:00Z",
	id: 5,
	event_type_id: 13,
	reason: "new Event",
	to_date: "2013-10-29T00:00:00Z",
	updated_at: "2013-10-24T06:32:14Z",
	user_id: 9
	created_at: "2013-10-24T06:30:31Z",
	days: 0.5,
	from_date: "2013-10-25T00:00:00Z",
	id: 4,
	event_type_id: 13,
	reason: "personal work",
	to_date: "2013-10-25T00:00:00Z",
	updated_at: "2013-10-24T06:30:31Z",
	user_id: 8

Change the “eventAfterRender” method in jquery

$(document).ready(function() {
		var date = new Date();
		var d = date.getDate();
		var m = date.getMonth();
		var y = date.getFullYear();

		        height: 350,
		        color: '#ff0000',
				textColor: '#ffffff',
				backgroundColor: 'red',
				firstDay: 1,
		        theme: true,
			header: {
				left: 'prev,next today',
				center: 'title',
				right: 'month,agendaWeek,agendaDay'
			disableDragging: true,
			editable: true,
			eventSources: [{
			url: '/yourdata',					
			color: '#ff0000',
			textColor: '#ffffff',
			backgroundColor: '#ccc',
			border:'1px solid #7BD148',
			ignoreTimezone: false
        eventRender: function(event, element, date ) {
            element.attr('title', event.tip); // for tooltip
        eventAfterRender: function(event, element, view) {
		       if (event.half == "1") {
		        // half a day
		        var elementWidth = parseInt(90 * event.day_count);

		        // set width of element
		        jQuery(element).css('width', elementWidth + "px");
		        if (event.className == "holi_day") {
                $(element).find(".fc-event-title").css({"color": "#0000dd", "font-weight": "bold"  });

Now the event calendar show the holidy, halfday and fullday as below

event calendar

Implementation of Shorten URL using Bitly in Rails 3.x

URL shortening is a technique on the World Wide Web in which a Uniform Resource Locator (URL) may be made substantially shorter in length and still direct to the required page.

This is achieved by using an HTTP Redirect on a domain name that is short, which links to the web page that has a long URL. This is especially convenient for messaging technologies such as Twitter and Identical which severely limit the number of characters that may be used in a message.

Many web developers pass descriptive attributes in the URL to represent data hierarchies, command structures, transaction paths or session information. This can result in URLs that are hundreds of characters long and that contain complex character patterns. Such URLs are difficult to memorize and manually reproduce. As a result, long URLs must be copied-and-pasted for reliability. Thus, short URLs may be more convenient for websites.


First create an account at  “”
Get your API key by thefollowing URL



In rails 3.x, write the following gems in your gemfile

 gem ‘bitly’

Run “bundle install”


Add the following code in your controller

require ‘bitly’


Bitly recently released their version 3 API. From this 0.5.0 release, the gem will continue to work the same but also provide a V3 module, using the version 3 API. The standard module will become deprecated, as Bitly do not plan to keep the version 2 API around forever.

To move to using the version 3 API, call in you top of the controller:



To shorten a URL

bitly =‘your-bitly-user-id’,’your-bitly-api-key’)

page_url = bitly.shorten(‘your-url’)

shorten_url = page_url.shorten

It will generate the bitly URL like “

Validate RSS or ATOM feeds using FeedValidator in Rails

FeedValidator is an interface to the W3C Feed Validation online service based on its SOAP 1.2 support. It helps to find errors in RSS or ATOM feeds. In Rails app this can be done installing the gem.


You can install FeedValidator as a gem by writing in gem file:

gem  ‘feedvalidator’

Run   bundle install  to install the gem


Include the require ‘feed_validator’ into your controller


Create a migration file and edit the file to add the following fields.

class CreateFeeds < ActiveRecord::Migration
   def self.up
     create_table :feeds do |t|
       t.string :title

  def self.down
    drop_table :feeds


Validate your feed URL in your controller

 def create
    valid = false
    site_url = params[:feed][:title].sub(/(\/)+$/,'')
        v =
        if v.validate_url(site_url) && v.valid?
          valid = true
          @feed = => site_url,

        # Do nothing
    redirect_to request.referrer

Active Record Callbacks in Rails

Callbacks are a great technique for achieving simplicity and flexibility. Callbacks provide a means of hooking into an ActiveRecord object’s life-cycle. A hook is a technique that lets you trap some Ruby event with ActiveRecord, such as object creation. Callbacks are hooks that allow you to trigger logic before or after an alteration of the object state. Callback functions minimizing the length of codes in controllers.

Implementing Callbacks

There are four types of callbacks accepted by the callback macros:

  • Method references (symbol)
  • Callback objects
  • Inline methods (using a proc)
  • Inline eval methods (using a string) – deprecated.

Method references and callback objects are the recommended approaches, inline methods using a proc are sometimes appropriate (such as for creating mix-ins) and inline eval methods are deprecated.
Method Reference

The method reference callbacks work by specifying a protected or private method available in the object, like this:

class Post < ActiveRecord::Base
before_save :process_content

def process_content

Callback Objects

The callback objects have methods named after the callback, called with the record as the only parameter such as:

class BankAccount < ActiveRecord::Base


class EncryptionWrapper
def initialize(attribute)
@attribute = attribute

def before_save(record)
record.credit_card_number = encrypt(record.credit_card_number)

def encrypt(value)
# Secrecy is committed


So you specify the object you want messaged on a given callback. When that callback is triggered the object has a method by the name of the callback messaged.


Example of using a Proc for a callback:

class Person
before_save { |model| model.do_something }

Callback Reference

Here are the list of some callback functions

  • before_save

This method is called before an ActiveRecord object is saved.

  • after_save

Once the active record object saved some method will be fired in that scenario we have to use the after_save callback.

  • before_create

Called before creating a new object of the model

  • after_create

Called after creating new object and just before saving the records

  • before_update
  • after_update
  • before_validation
  • after_validation
  • before_validation_on_create
  • after_validation_on_create
  • before_validation_on_update
  • after_validation_on_update
  • before_destroy
  • after_destroy