Explore more about .nil? .empty? .blank? .present? in Ruby on Rails

nil?, empty? and blank? and .present? are little bit confusing.

We as a Developer needs to be careful in using them and it is better that we digest the details before using it.


  • It is Ruby method
  • It can be used on any object and is true if the object is nil.
  • “Only the object nil responds true to nil?” – RailsAPI

In Ruby, all classes inherit from the Object class. nil? is a method of Object; therefore, unless explicitly overridden, all classes have access to nil?. To better understand how Ruby expresses the concept of a non existent object, we need to look at its pseudo-variable nil. The same idea in other languages is often mapped to the primitive type, null or NULL. Depending on the language, NULL may point to nothing at all. Ruby differs here, in that, nil references an actual class called NilClass which exposes methods. This is why it’s possible to do seemingly illogical things like:

nil.nil?    => true
When calling on an object that is non existent, invalid or explicitly set to nil, an instance of the singleton NilClass is returned.

A few examples will illustrate how this works.

posts= {:name=> “my post”, :description=> “my description”}

posts[:name]   => nil
posts[:name].class  => NilClass
posts[:name].nil? => true
posts[:description].nil? => false

my_test_var = nil
my_test_var .nil? => true

[].nil? => false

“”.nil? => false

0.nil? => false

false.nil? => false


Unlike nil?, empty? is only available on some Ruby objects. String, Hash and Array are a few of the classes that implement it. When calling empty? the receiving object is being checked to see if it possesses a non-nil value or values. empty? (at least for the mentioned classes) returns either true or false.

  • It is Ruby method
  • can be used on strings, arrays and hashes and returns true if:

String length == 0
Array length == 0
Hash length == 0

  • Running .empty? on something that is nil will throw a NoMethodError

[“name”, “title”, “description”].empty? => false

[“”].empty? => false

[].empty? => true

{}.empty?=> true

“”.empty?=> true

0.empty? => NoMethodError: undefined method `empty?’ for 0:Fixnum

my_test_var2 = nil
my_test_var2 .empty? = > NoMethodError: undefined method `empty?’ for nil:NilClass
The last example above clearly illustrates why one would get unexpected results when trying to do things like this:

dog = {:name => “Beauregard”}
puts “What kind?” if dog[:breed].empty?
=> NoMethodError: undefined method `empty?’ for nil:NilClass

# Use nil? instead.
puts “What kind?” if dog[:breed].nil?
=> What kind?


  • It is Rails method
  • operate on any object as well as work like .empty? on strings, arrays and hashes.
  • It also evaluates true on strings which are non-empty but contain only whitespace:

“An object is blank if it‘s false, empty, or a whitespace string.
For example, “”, ” “, nil, [], and {} are blank.”

For instance, I often use blank? when operating on form field values that are considered optional by a model. Going back to the dog hash, we can see how blank? simplifies testing for values.

nil.blank? = true
[].blank? = true
{}.blank? = true
“”.blank? = true
5.blank? == false
dog = {:name => “Beauregard”}
puts “What kind?” if dog[:breed].blank?
=> What kind?

dog = {:name => “Beauregard”, :breed => “”}
puts “What kind?” if dog[:breed].blank?
=> What kind?
” “.blank? == true” “.empty? == false


Quick tip: !obj.blank? == obj.present?
activesupport/lib/active_support/core_ext/object/blank.rb, line 17 # (Ruby 1.9)

def present?


Ruby on Rails Interview Questions and Answers

Hey guys, hope you’re having a fine day. Today, my post will be to help answer some of the most difficult technical interview questions; because, interviews can always be stressful even for job seeker who have attended countless interviews. I believe the best way to reduce the stress is to be prepared.

Here are some of the most frequently asked questions and how to answer them confidently.

What is agile development

A:Agile methodology is anadaptaive methodology, its people
Here are some of the other characteristices of the Agile
1. Delivery frequently.
2. Good ROI for client.
3. Test frequently.
4. Collaborative approach.
Agile methodology is on daily basis report. How much work we have completed on that day and how much work is still pending…it gives the clear picture but the req are not defined beforehanditself completely.. req will be changing….

Why Ruby on Rails?

A: There are lot of advantages of using Ruby on Rails(ROR)
1. DRY Principal
2. Convention over Configuration
3. Gems and Plugins
4. Scaffolding
5. Pure OOP Concept

What is MVC? and how it Works?
A: MVC tends for Model-View-Controller, used by many languages like PHP, Perl, Python etc. The flow goes like below image



for Example your url is something like this:


here users is your controller and new is your method, there must be a file in your views/users folder named new.html.erb, so once the submit button is pressed, User model or whatever defined in the rhtml form_for syntax, will be called and values will be stored into the database.

What is ORM in Rails?
A: ORM tends for Object-Relationship-Model, it means that your Classes are mapped to table in the database, and Objects are directly mapped to the rows in the table.

What is Ruby Gems?
A. Ruby Gem is a software package, commonly called a “gem”. Gem contains a packaged Ruby application or library. The Ruby Gems software itself allows you to easily download, install and manipulate gems on your system.

What is Gemfile and Gemfile.lock?
A. The Gemfile is where you specify which gems you want to use, and lets you specify which versions. The Gemfile.lock file is where Bundler records the exact versions that were installed. This way, when the same library/project is loaded on another machine, running bundle install will look at the Gemfile.lock and install the exact same versions, rather than just using the Gemfile and installing the most recent versions. (Running different versions on different machines could lead to broken tests, etc.) You shouldn’t ever have to directly edit the lock file.
Get more Explanations on Gem file here.

What is Active record

A-There are many reasons why Active Record is the smart choice
Simplified configuration and default assumptions (Convention over Configuration).
Associations among objects.
Automated mapping b/w tables and classes and b/w columns and attributes.
Data Validations.
Inheritance hierarchies.
Direct manipulation of data as well as schema objects.
Database abstraction through adapters.
Logging support.
Migration support.
Active Record integrated in other emerging frameworks like Merb.

How you run your Rails application without creating databases?
A. You can run your application by uncommenting the line in environment.rb
path=> rootpath conf/environment.rb
config.frameworks- = [action_web_service, :action_mailer, :active_record

What are the servers supported by ruby on rails?
A. Ruby Supports a number of Rails servers (Mongrel, WEBRICK, PHUSION, Passenger, etc..depending on the specific platforms).
For each Rails application project, RubyMine provides default Rails run/debug configurations for the production and development environments.

What is the difference between a plugin and a gem?
A. A gem is just ruby code. It is installed on a machine and it’s available for all ruby applications running on that machine. Rails, rake, json, rspec — are all examples of gems.
Plugin is also ruby code but it is installed in the application folder and only available for that specific application.
Sitemap-generator, etc.
In general, since Rails works well with gems you will find that you would be mostly integrating with gem files and not plugins in general. Most developers release their libraries as gems.

What is restful in rails

A.Stands for REpresentational State Transfer


What is passanger
A. Easy and robust deployment of ruby on rails app on appache and ngix webservers
passenger is an intermediate to run the ruby language in linux server

 What is request.xhr?
A: A request.xhr tells the controller that the new Ajax request has come, It always return TRUE or FALSE

What is the Difference between Static and Dynamic Scaffolding?
A: The Syntax of Static Scaffold is like this:
ruby script/generate scaffold User Comment
Where Comment is the model and User is your controller, So all n all static scaffold takes 2 parameter i.e your controller name and model name, whereas in dynamic scaffolding you have to define controller and model one by one.

What is Session and Cookies?
A: Session: are used to store user information on the server side.
cookies: are used to store information on the browser side or we can say client side
Session : say session[:user] = “srikant” it remains when the browser is not closed

What is the difference between form_for and form_tag

A. form_tag and form_for both are used to submit the form and it’s elements.
The main difference between these two is the way of managing objects related to that particular model is different.
We should use “form_for” tag for a specific model
It performs the “standard http post” which is having fields related to active record (model) objects

It creates a form as a normal form. form_tag also performs the “standard http post” without any model backed and has normal fields. This is mainly used when specific data need to be submitted via form.
It just creates a form tag and it is best used for non-model forms.


<% form_tag ‘/articles’ do -%>
<%= text_field_tag “article”, “firstname” %>
<% end -%>

Difference between ruby 1.8.7 and 1.9.2

A.Ruby 1.9 – Major Features

gems is (mostly) built-in now
if statements do not introduce scope in Ruby.

-{“a”,”b”} No Longer Supported
-Array.to_s Now Contains Punctuation
-Colon No Longer Valid In When Statements

What are the engines in mysql
Ans: In previous versions of MySQL, MyISAM was the default storage engine. In our experience, most users never changed the default settings. With MySQL 5.5, InnoDB becomes the default storage engine.

What is the difference between include and extend
A.include makes the module’s methods available to the instance of a class, while
extend makes these methods available to the class itself.

When you use include, the module’s methods are added to the instances of the class. The log method is:

Not available at the class level
Available at the instance level
Not available at the class level again

When you use extend, the module’s methods are added to the class itself. The log method is:

Available at the class level.
Not available at the instance level.
Available at the class level.

What is the difference between lambada and proc

A.proc and Lambda are used to create code blocks. After creating them, we can pass them around our code, just like variables.

How to call method dynamically

A.[“foo”, “bar”].each do |method|

How to create a method dynamically

A.class Message
[:hello, :goodbye].each do |method_name|
define_method method_name do |arg|
“#{method_name} #{arg}”

Message.instance_methods false #=> [:hello, :goodbye]
Message.new.hello ’emre’ #=> “hello emre”
Message.new.goodbye ’emre’ #=> “goodbye emre”

How to use Nested routes in ROR

The easiest way to create a nested route, is to use the :has_many keyword like that:

# /config/routes.rb
map.resources :projects, :has_many => :tasks

# and the correspondent task resource
map.resources :tasks

Adding the second routes, that defines a RESTful route to :tasks, depends if you would like to allow an access to the Task resource, without the project context, this is not a must.

What things we can define in the model?
A: There are lot of things you can define in models few are:
1. Validations (like validates_presence_of, numeracility_of, format_of etc.)
2. Relationships(like has_one, has_many, HABTM etc.)
3. Callbacks(like before_save, after_save, before_create etc.)
4. Suppose you installed a plugin say validation_group, So you can also define validation_group settings in your model
5. ROR Queries in Sql

How many Types of Relationships does a Model has?
A: * (1) has_one
* (2) belongs_to
* (3) has_many
* (4) has_many :through

What is asset pipeline
A.asset pipeline which enables proper organization of CSS and JavaScript

What is observer in rails

A:Observer classes respond to life cycle callbacks to implement trigger-like behavior outside the original class.

Rails observers are sweet, You can observe multiple models within a single observer

First, you need to generate your observer:

command – rails g observer Auditor

-observer classes are usually stored in app/models with the naming convention of app/models/audit_observer.rb.

In order to activate an observer, list it in the config.active_record.observers configuration setting in your config/application.rb file.

config.active_record.observers = :comment_observer, :signup_observer
Observers will not be invoked unless you define these in your application configuration.
Reference: http://apidock.com/rails/ActiveRecord/Observer
What is rails sweeper
One sweeper can observe many Models, and any controller can have multiple sweepers.

Difference between -%> and %> in rails
A:The extra dash makes ERB not output the newline after the closing tag. There’s no difference in your example, but if you have something like this:

<% if true -%>
<% end -%>

It’ll produce:


and not this:


Difference between render and redirect?
Redirect is a method that is used to issue the error message in case the page is not found or it issues a 302 to the browser. Whereas, render is a method used to create the content.

-Redirect is used to tell the browser to issue a new request. Whereas, render only works in case the controller is being set up properly with the variables that needs to be rendered.

-Redirect is used when the user needs to redirect its response to some other page or URL. Whereas, render method renders a page and generate a code of 200.

-Redirect is used as:
redirect_to: controller => ‘users’, :action => ‘new’

-Render is used as:
render: partial
render: new -> this will call the template named as new.rhtml without the need of redirecting it to the new action.

What is the use of rake db:reset

A.db:create——- creates the database for the current env
db:create:all ———creates the databases for all envs
db:drop ———-drops the database for the current env
db:drop:all ———-drops the databases for all envs
db:migrate ———-runs migrations for the current env that have not run yet
db:migrate:up ——–runs one specific migration
db:migrate:down ——-rolls back one specific migration
db:migrate:status —–shows current migration status
db:migrate:rollback —rolls back the last migration
db:forward ————advances the current schema version to the next one
db:seed (only) ———runs the db/seed.rb file
db:schema:load ————loads the schema into the current env’s database
db:schema:dump ———dumps the current env’s schema (and seems to create the db aswell)

db:setup ————-runs db:schema:load, db:seed

db:reset ———-runs db:drop db:setup
db:migrate:redo ———runs (db:migrate:down db:migrate:up) or (db:migrate:rollback db:migrate:migrate) depending on the specified migration
db:migrate:reset ——runs db:drop db:create db:migrate

What is eagerloading
A.-One way to improve performance is to reduce the number of database queries through eager loading.
-You can know where we need eager loading through “Bullet’ Gem

How to use sql db or mysql db. without defining it in the database.yml

What are helpers and how to use helpers in ROR?
A. Helpers (“view helpers”) are modules that provide methods which are automatically usable in your view. They provide shortcuts to commonly used display code and a way for you to keep the programming out of your views. The purpose of a helper is to simplify the view. It’s best if the view file (RHTML/RXML) is short and sweet, so you can see the structure of the output.

What is Active Record?
A. Active Record are like Object Relational Mapping(ORM), where classes are mapped to table and objects are mapped to colums in the table

Ruby Supports Single Inheritence/Multiple Inheritence or Both?
A. Ruby Supports only Single Inheritnece

How many types of callbacks available in ROR?
A. * (-) save
* (-) valid
* (1) before_validation
* (2) before_validation_on_create
* (-) validate
* (-) validate_on_create
* (3) after_validation
* (4) after_validation_on_create
* (5) before_save
* (6) before_create
* (-) create
* (7) after_create
* (8) after_save

How to use two database into a Single Application?

A. http://magicmodels.rubyforge.org/magic_multi_connections/, According to this link : ActiveRecord models are allowed one connection to a database at a time, per class. Ruby on Rails sets up the default connection based on your database.yml configuration to automatically select development, test or production.
But, what if you want to access two or more databases – have 2+ connections open – at the same time. ActiveRecord requires that you subclass ActiveRecord::Base.
That prevents you doing migrations from one database to another. It prevents you using one set of model classes on two or more databases with the same schema.
Magic Multi-Connections allows you to write your models once, and use them for multiple Rails databases at the same time. How? Using magical namespacing.

To do this :
[A] sudo gem install magic_multi_connections
[B] require ‘magic_multi_connections’
Add the following to the bottom of your environment.rb file
You can also find examples on this link : http://magicmodels.rubyforge.org/magic_multi_connections/

“Updated Set of Questions for Rails 3”

What is the difference between the Rails version 2 and 3?
A. * (1) Introduction of bundler (New way to manage your gem dependencies)
* (2) Gemfile and Gemfile.lock (Where all your gem dependencies lies, instead of environment.rb)
* (3) A new .rb file in config/ folder, named as application.rb (Which has everything that previously environment.rb had)
* (4) Change in SQL Structure: Model.where(:activated => true)
* (5) All the mailer script will now be in app/mailers folder, earlier we kept inside app/models.
* (6) Rails3-UJS support. for links and forms to work as AJAX, instead of writing complex lines of code, we write :remote => true
* (7) HTML 5 support.
* (8) Changes in the model based validation syntax: validates :name, :presence => true
* (9) Ability to install windows/ruby/jruby/development/production specific gems to Gemfile.
group :production do
gem ‘will_paginate’

What is bundler?
A: Bundler is a new concept introduced in Rails3, which helps to you manage your gems for the application. After specifying gems in your Gemfile, you need to do a bundle install. If the gem is available in the system, bundle will use that else it will pick up from the rubygems.org.

What is the Newest approach for find(:all) in Rails 3?
A: Model.where(:activated => true)

Ruby Interview Questions :

What are the variable in ruby

A.1 Local Variables – foobar
2 Instance Variables – @foobar
3 Class Variables – @@foobar
4 Global Variables – $foobar
Name Begins With Variable Scope
$ A global variable
@ An instance variable
[a-z] or _ A local variable
[A-Z] A constant
@@ A class variable

Difference between “and” and && in Ruby?
A.and is the same as && but with lower precedence.

Difference between method overloading and method overwriting

A.def: In Method Overloading, Methods of the same class shares the same name but each method must have different number of parameters or parameters having different types and order.

Method Overloading means more than one method shares the same name in the class but having different signature.
In Method Overloading, methods must have different signature.
Method Overloading does not require more than one class for overloading.

Def:In Method Overriding, sub class have the same method with same name and exactly the same number and type of parameters and same return type as a super class.

Method Overriding means method of base class is re-defined in the derived class having same signature.
In Method Overriding, methods must have same signature.
Method Overriding requires at least two classes for overriding.

What is the Notation used for denoting class variables in Ruby?
A:We can know a variable as “Class variable’s” if its preceeded by @@ symbols.

What is the use of Destructive Method?
A:Distructive methods are used to change the object value permanently by itself using bang (!) operator.
‘sort’ returns a new array and leaves the original unchanged.
‘sort!’ returns the same array with the modification.
The ‘!’ indicates it’s a destructive method. It will overwrite the current array with the new result and returns it.

What is the use of load and require in Ruby?
A:The require() method is quite similar to load(), but it’s meant for a different purpose.
You use load() to execute code, and you use require() to import libraries.

What is the use of Global Variable in Ruby?
A:Syntatically, a global variable is a variable whose name begins with $
Global variables in Ruby are accessible from anywhere in the Ruby program, regardless of where they are declared.
$welcome = “Welcome to Ruby Essentials”

How does nil and false differ?
A:nil cannot be a value, where as a false can be a value
A method returns true or false in case of a predicate, other wise nil is returned.
false is a boolean data type, where as nil is not.
nil is an object for NilClass, where as false is an object of for FalseClass

What is the diffence betweet symbol and string
A. Symbols have two nice properties compared to strings which can save you memory and CPU time
The difference remains in the object_id, memory and process time for both of them when used together at one time
Strings are considered as mutable objects. Whereas, symbols, belongs to the category of immutable
Strings objects are mutable so that it takes only the assignments to change the object information. Whereas, information of, immutable objects gets overwritten

How to use super key word

A.Ruby uses the super keyword to call the superclass implementation of the current method.
Within the body of a method, calls to super acts just like a call to that original method.
The search for a method body starts in the superclass of the object that was found to contain the original method.
def url=(addr)
super (addr.blank? || addr.starts_with?(‘http’)) ? addr : http://#{addr}

How is visibility of methods change in Ruby?

What is a Class Instance Variable

What are the rules and conventions to be followed in Ruby for naming a method?

How is class method defined in Ruby?

What are the Operators available in Ruby?

What are the looping structure available in Ruby?

What is the scope of local variable?

What are the OOP supported by Ruby?

If Ruby over PHP, Why?

Garbage collection in Ruby?

Environment Variables in Ruby?

What are Float, Dig and Max?
Ans.Float class is used whenever the function changes constantly. It acts as a sub class of numeric. They represent real characters by making use of the native architecture of the double precision floating point.
Max is used whenever there is a huge need of Float.
Dig is used whenever you want to represent a float in decimal digits.
What is Ruby Code blocks?

What kind of conditions ruby support?

Difference between puts and print
Ans.puts adds a newline to the end of the output. print does not.

Is there any technology apart from agile which we can use?

What are the servers supported by ruby on rails application?

Passenger running on Apache. Easy to set up, low memory usage, and well supported.
nginx with puma(it is a multi-threaded high performance webserver written in Ruby).

What is Meta-programming? How you are using it inside your rails application?

What is has_many?
Ans. It is a way of defining relationships among models. Correct, and Do you guys really know has_many is also an example of Meta-programming? Wondering, How?

What is TDD and BDD?
A: Test-Driven-Development and Behavior-Driven-Development

What is rspec, cucumber and Watir? And what it has to do with TDD and BDD?

What is the difference between ‘&&’ and ‘||’ operators?

A. “&&” has higher precedence than “||” like in most other mainstream languages; but “or” and “and” in ruby have the same(!) precedence level!
so if you write
(func1 || func2 && func3), it’s (func1 || (func2 && func3))
(func1 or func2 and func3) is interpreted as ((func1 or func2) and func3)
because of shorcircuiting, if func1 is true, both func2 and func3 won’t be called at all in the first example
but in the second example func3 WILL be called!
this difference is subtile enough that I really do not recommend newbies to use “and” and “or” in ruby at all.

What is the Purpose of “!” and “?” at the end of method names?
A. It’s “just sugarcoating” for readability, but they do have common meanings:
Methods ending in ! perform some permanent or potentially dangerous change; for example:
Enumerable#sort returns a sorted version of the object while Enumerable#sort! sorts it in place.
In Rails, ActiveRecord::Base#save returns false if saving failed, while ActiveRecord::Base#save! raises an exception.
Kernel::exit causes a script to exit, while Kernel::exit! does so immediately, bypassing any exit handlers.
Methods ending in ? return a boolean, which makes the code flow even more intuitively like a sentence — if number.zero? reads like “if the number is zero”, but if number.zero just looks weird.
In your example, name.reverse evaluates to a reversed string, but only after the name.reverse! line does the name variable actually contain the reversed name. name.is_binary_data? looks like “is name binary data?”.

Just remember it in simple
In Ruby the ? means that the method is going to return a boolean and the ! modifies the object it was called on. They are there to improve readability when looking at the code.

How can you list all routes for an application?
A) By writing rake routes in the terminal we can list out all routes in an application.

What is rake?
A) rake is command line utility of rails. “Rake is Ruby Make, a standalone Ruby utility that replaces the Unix utility ‘make’, and uses a ‘Rakefile’ and .rake files to build up a list of tasks. In Rails, Rake is used for common administration tasks, especially sophisticated ones that build off of each other.”

Putting in simple word : “rake will execute different tasks(basically a set of ruby code) specified in any file with .rake extension from comandline.”

What are the differences between MongoDB and Redis?

A) Redis is a key value store while mongoDB is a document store.
  1.Data model
Document oriented, JSON-like. Each document has unique key within a collection. Documents are heterogenous.
Key-value, values are:

  • Lists of strings
  • Sets of strings (collections of non-repeating unsorted elements)
  • Sorted sets of strings (collections of non-repeating elements ordered by a floating-point number called score)
  • Hashes where keys are strings and values are either strings or integers After Wikipedia.

Disk, memory-mapped files, index should fit in RAM.
Typically in-memory.
By key, by any value in document (indexing possible), Map/Reduce.
By key.

What are the new features of Rails4?
1. Ruby Versions
2. ‘Gemfile’
3. ‘Threadsafe’ by Default
4. No More vendor/plugins
5. New Testing Directories
6. Strong Parameters
7. Renamed Callback
10. Queuing system
13. Cache Digests (Russian Doll Caching)
14. Turbolinks

More Questions and Answers of this will be published very soon 🙂 

‘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 => 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}"}
		@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}"}
	  params[:for_year]=Time.now.strftime("%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 bit.ly  “https://bitly.com/a/sign_up?rd=/”
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 = 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.


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 = W3C::FeedValidator.new
        if v.validate_url(site_url) && v.valid?
          valid = true
          @feed = Feed.new(:title => 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
before_save EncryptionWrapper.new(“credit_card_number”)

after_initialize EncryptionWrapper.new(“credit_card_number”)

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 Proc.new { |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