Category Archives: hack

Unstubbing methods in Mocha

Recently I needed to ‘unstub’ a method in Mocha. Browsing Mocha documentation and googling yielded no results. Apparently, Mocha doesn’t support a concept of ‘unstubbing’, i.e. recovering original implementation of a method that has been stubbed. After a little hacking, I found out that it’s quite easy (though not necessarily elegant) to call original implementation.

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

each-require anti-pattern

This is going to be a little rant. This little anti-pattern I see all over in Ruby code by various people:

%w{yaml fileutils}.each { |lib| require lib }

I cannot understand why do people write it like this. This is neither shorter nor easier to read than the ‘normal’ version:

require 'yaml' 
require 'fileutils'

Continue reading