I am a web developer working with
SlideShare, Delhi. This is my Website.

Blog


0 Comments

Dynamic is_ ? methods for boolean attributes of a model

08.24.10 Posted in Blog by admin

A very common pattern observed in Rails models is a series of “is_{attribute}?” instance methods. Here, ‘attribute’ is usually a boolean column. I got tired of defining these similar methods. And adding to the misery, if the model structure changes to add another boolean field, you need to define another clone of the same method!

So, I ended up using this little trick. Ruby meta programming awesomeness helped, of course.

Consider a minimalistic Model called ‘User’ with an underlying ‘users’ table in the database.

User
Id, Login, Name, Email, Verified, Blocked, Available

I know the schema can be altered to take these 3 into a single field called “state” or something on those lines, but this is just a simple example. Here, the last 3 attributes are boolean. We need to define methods “is_verified?” , “is_blocked?” , “is_available?”.

Usually, we would define 3 instance methods or named_scopes to achieve the objective. Like so:

def is_verified?
self.verified
end

def is_blocked?
self.blocked
end

def is_available?
self.available
end

Annoying, right? Let’s try this:

def self.boolean_attributes
self.columns_hash.reject{|k,v| (v.type.to_s != 'boolean') }.keys
end

self.boolean_attributes.each do |boolean_attribute|
define_method "is_#{boolean_attribute}?" do
!!self.send(boolean_attribute)
end
end

There. If there are 12 boolean attributes, you have 12 methods defined dynamically! And if you change the schema, you still have “is_{new_attribute}?” in place automatically.


5 Comments

Ruby on Rails views : Time ago in words for string time

07.27.10 Posted in Blog by admin

I worked my way around an interesting information tidbit discovery yesterday. The use case seemed pretty simple and direct. I needed to display the “n hours ago” text in my view. I used the awesome view helper ‘time_ago_in_words’ to do that and it worked, well almost.

Here’s what I’m talking about:
In console,

time_string = "2010-07-21 11:52:31"
helper.time_ago_in_words(time_string) # => about 5 hours

The catch here is that the “5 hours” duration is incorrect. This was hardly 5 minutes ago! So, the problem here was in time zones.
By default,

time_string.to_time # => Wed Jul 21 11:52:31 UTC 2010

Notice the time zone offset. It has been set to “UTC” by default. But the original time zone of this string time was different. And the tricky part is, it was different for different environments. So how’d we get past this? Here’s the entire snippet:

def custom_time_ago_in_words(time_str)
time = time_str.to_time + (-Time.zone_offset(Time.now.zone))
"#{time_ago_in_words(time)} ago"
end

This essentially adjusts the time according to the server time zone and gives correct output as “5 minutes ago”.


0 Comments

ActiveRecord Object to Hash assignment in Ruby on Rails

07.13.10 Posted in Blog by admin

I find a frequent scenario in Ruby on Rails code base. A local hash variable is assigned a partial subset of an ActiveRecord object, or worse the variable gets the entire AR object. And may be you don’t already do it the way I have seen it, but its still worth discussing, being as frequent a requirement as it is.

1. If we want to assign an entire AR object to a local hash:
A direct assignment is possible with “attributes”

local_hash = session_user.attributes

the ‘local_hash’ now has an attribute-value hash of the session_user object, an ActiveRecord object of model User ]

2. If we need the local_hash to have only a subset of the AR object attributes:

desired_keys = ['address' , 'zipcode' , 'city' , 'country']
local_array = session_user.attributes.select{|key,value| desired_keys.include?(key) }
local_hash = Hash[*local_array.flatten]

the ‘local_hash’ now has only the desired attribute values. This can easily be extended by simply adding more keys to ‘desired_keys’.
Instead of what I usually see,

local_hash = {
'address' => session_user.address,
'zipcode' => session_user.zipcode,
'city' => session_user.city,
'country' => session_user.country
}

What do you think of this snippet? Is there a shorter/smarter way of doing this? Think on!


7 Comments

YAML Oddity for Ruby arrays

07.02.10 Posted in Blog by admin

I discovered this interesting nugget of oddity today. While normal Ruby arrays are ‘comma separated” and space agnostic ie.

>> array = [2,3 ,4, 5]
=> [2, 3, 4, 5]
>> array.size
=> 4
>> array_spaces = [2 , 3 , 4 , 5]
=> [2, 3, 4, 5]
>> array_spaces.size
=> 4

In case of YAML, the spaces between array elements makes a difference. A much needed code snippet :

A file ‘myfile.yml’

array: [ 1 , 2 ,3, 4]
array_spaces: [1 , 2 , 3 , 4]

Loading this file in ‘irb’:

>> f =YAML.load_file('myfile.yml')
=> {"array"=>[1, "2 ,3", 4], "array_spaces"=>[1, 2, 3, 4]}
>> f["array"]
=> [1, "2 ,3", 4]
>> f["array"].size
=> 3
>> f["array_spaces"]
=> [1, 2, 3, 4]
>> f["array_spaces"].size
=> 4

Now that’s not Ruby-ish. But then, as a seasoned co-developer pointed out, YAML should be language agnostic. I still find it a bit odd, though. Hmmm, interesting. Point taken.


0 Comments

Ruby on Rails Must follow RSS feeds

05.20.10 Posted in Blog by admin

Ruby on Rails community is fast growing. Too much is happening, and too fast. Its important to keep ourselves abreast of the latest in our community. Following are some RSS feeds I follow religiously [ well, I try]. So configure your favorite Reader and put on your reading caps:

Always begin by looking at RoR guides:
Ruby on Rails guides

The BEST Ruby on Rails resource that gives a consolidated set from many relevant RoR resources:
Drink Rails

The renowned railscasts
Railscasts

RoR @SlideShare
Ruby @SlideShare
Rails @SlideShare

Awesome RoR screen casts. Short and concise.
Ruby Plus

Not very frequently updated, but has good content.
Monkey on Rails

Elaborate content on a wide variety of RoR subjects. By Yehuda Katz is a member of the Ruby on Rails core team.
Katz Got Your Tongue

Usually covered by “drinkrails”. Good resource.
Lindsaar Net

Updated, concise and good information resource.
Rails Dispatch

Latest on Rails. Tonnes of new and interesting stuff.
Rails Inside

Short concise everyday Rails tips.
Rails Quick Tips

The latest developments in Rails, all in one place
Riding Rails

Rails notes. Solutions to every day “how-tos”.
Rails Notes

Get your Ruby right with quick Ruby tips.
Ruby Quick Tips

Awesome Ruby resource. 5 minutes of Ruby goodness.
Ruby5

Another amazing Ruby resource. Concise episodes. Really useful.
Ruby Pulse Episodes

A good collection.
Rails Coach


0 Comments

Databases don’t bite!

02.19.10 Posted in Blog by admin

Checkout my post at Sapna Blog.

http://sappsdreams.wordpress.com/2010/02/19/databases-dont-bite/