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

Step#1

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

Benefits

  • 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

Problem

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

Conclusion

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

 

Advertisements

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

Step-1

Add gems inside asset group in your Gemfile

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

    gem ‘twitter-bootstrap-rails’
end

Step-2

bundle install

Step-3

rails generate bootstrap:install less

Step – 4

Generating layouts and views

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

example
rails g bootstrap:layout application fluid

Step-5

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

rails g bootstrap:themed [RESOURCE_NAME]

 

Example:

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:

http://www.rubyonrails.org/

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

rails

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 => event.id, :title => event.user.name + "   ( " + 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}"}
		end
		@holiday.each do |hol|
		  events << {:id => hol.id, :title => hol.name + "   ( HOLIDAY )", :day_count => 1 ,:tip => "Type:Holiday  Resson:" +  hol.name || "", :half=> 0, :color=> "#B6B6B6", :className=>"holi_day",:description => hol.description || "Some cool description here...", :start => "#{hol.h_date.iso8601}", :end => "#{hol.h_date.iso8601}"}
		end
		 events
	else
	  params[:for_year]=Time.now.strftime("%Y") unless params[:for_year]
		events = Event.where("YEAR(from_date)=?",params[:for_year]).order("created_at desc")
	end
    respond_to do |format|
      format.html 
	   format.xml  { render :xml => events }
      format.json { render json: events}
    end
  end

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();

		$('#calendar').fullCalendar({ 
		        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.

Step#1

First create an account at bit.ly  “https://bitly.com/a/sign_up?rd=/”
Get your API key by thefollowing URL

“http://bit.ly/account/your_api_key/”

Step#2

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

 gem ‘bitly’

Run “bundle install”

Step#3

Add the following code in your controller

require ‘bitly’

Step#4

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:

Bitly.use_api_version_3

Step#5

To shorten a URL

bitly = Bitly.new(‘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 “http://bit.ly/7BWXcQ

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.

Step#1

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

gem  ‘feedvalidator’

Run   bundle install  to install the gem

Step#2

Include the require ‘feed_validator’ into your controller

Step#3

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
       t.timestamps
     end
  end

  def self.down
    drop_table :feeds
  end
end

Step#4

Validate your feed URL in your controller

 def create
    valid = false
    site_url = params[:feed][:title].sub(/(\/)+$/,'')
      begin
        v = W3C::FeedValidator.new
        if v.validate_url(site_url) && v.valid?
          valid = true
          @feed = Feed.new(:title => site_url,
          @feed.save
        end
      rescue
        # Do nothing
      end
    redirect_to request.referrer
  end

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

private
def process_content
self.content.strip!
end
end

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
before_save EncryptionWrapper.new(“credit_card_number”)

after_initialize EncryptionWrapper.new(“credit_card_number”)
end

class EncryptionWrapper
def initialize(attribute)
@attribute = attribute
end

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

private
def encrypt(value)
# Secrecy is committed
end

end

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.

Proc

Example of using a Proc for a callback:

class Person
before_save Proc.new { |model| model.do_something }
end

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