Category Archives: ActiveRecord

Looping in a no man’s land

…or: how to put class scope to use

The class scope, i.e. the space inside class declaration, but outside method definitions, is a no man’s land in many languages (particularly in Java). By this I mean that you can define methods, variables, and other classes there and you can even execute some code (in variable initializations) but nothing more. Fortunately, in Ruby empty space between method definitions can be filled with all kinds of useful, executable code. Let’s check a few examples.

Continue reading


Extending Rails’ magic finders

One of the many cool things of Ruby on Rails are magic finders, or Dynamic attribute-based finders as the documentation calls them. Thanks to them we can write:

User.find_by_login_and_status(some_login, 1)

instead of:

User.find(:first, ['login = ? and status = ?', some_login, 1])

The first form is shorter and easier for human to parse.

Unfortunately, we can only combine attributes using and operator, but the possibility to use or and not operators would also be nice. And, as always when using Ruby on Rails, when we find that library is lacking some feature, we can easily add it. Let’s see how to do it.
Continue reading