The blog of Tobin

Tobins nerd blog on .NET, Software, Tech and Nice Shiny Gadgets.

Wednesday, May 04, 2005

Extending Ruby Types (as seen in Rails)

I was looking through some of the Rails source code today, and saw something that I simply love. "David" had added some nifty features to the number class. For example, with these extensions you can now write super-verbose code such as:

puts 1.hour.from_now
>Wed May 04 15:15:53 GMT Daylight Time 2005

puts 2.weeks.from_now
>Wed May 18 15:15:53 GMT Daylight Time 2005

puts 10.minutes.ago
>Wed May 04 15:05:53 GMT Daylight Time 2005

This stuff is great! It's easily achieved too, in fact, you can even open up the interactive shell and extend classes right there. It just involves redefining the class with the extra functions you want. See the Rails Fixnum example I was looking at, which show how the above examples work.

0 Comments:

Post a Comment

<< Home