Chaining methods using ‘tap’ method

The Ruby tap method is one the methods that makes you wonder about the thought that has gone behind writing the language. It belongs to Ruby 1.8.7 and above.

What does tap do
Tap allows you to create a chain of methods while working on the intermediate results and returning the object at the end.

Ruby Documentation

For example

[1,2,3,4].tap{|o| o << 100 } # [1,2,3,4,100]

I find this comes in really handy especially if your working with named_scopes. Though the technique may not be the best but I find it to be a better option than using eval on user input. So here is the situation.

We have the user enter certain information on the kind of users he wishes to see on the screen. Ex: Customers, Adminstrators, Managers

He could also specify if the user is active or inactive (indicating whether he has full access to his account or not).

So based on his input we generate a query string for method chaining. Assuming that I have a named_scope for each situation in my user model

result_set.tap{|o| (o.blank?) ? o << "experts" : o << ".experts" if params[:type] == "Expert"}.
        tap{|o| (o.blank?) ? o << "customers" : o << ".customers" if params[:type] == "Customer"}.
        tap{|o| (o.blank?) ? o << "adminstrators" : o << ".adminstrators" if params[:type] == "Adminstrator"}.
        tap{|o| (o.blank?) ? o << "activated" : o << ".activated" if params[:activated] == 'true'}.
        tap{|o| (o.blank?) ? o << "deactivated" : o << ".deactivated" if params[:activated] == 'false'}
    end

   User.instance_eval { eval(result_set) }

How cool is that. 🙂