Category Archives: method_missing

Eliminating code duplication with metaprogramming

Duplication of code is one of the worst code smells. It should be refactored in order to keep DRY if only possible. This is generally easy. But what if the code itself is not duplicated, but its structure is? That could be a little bit more difficult, but with Ruby‘s metaprogamming facilities it’s not that hard. Read on to see how.

Continue reading

Advertisements

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