Want to reuse variable and not pollute scope? Meet Object#tap()

This is my latest favorite, little, neat feature (it appeared around ruby 1.9 but the idea is simple, and it can be implemented in any decent language*… No php, you can’t play that game – too difficult for you). For older rubies you can monkeypatch it, but you should probably upgrade – with tests it’s really simple.

so you have

set :foo, "/home/me/foo"
set :bar, "/home/me/foo/bar"

you want to keep it DRY, so

home = "/home/me/";
set :foo, "#{home}foo"
set :bar, "#{home}foo/bar"

but one of the option to avoid polluting namespace with home variable is to use tap() method:

"/home/me/".tap do |h|
  set :foo, "#{h}foo"
  set :bar, "#{h}foo/bar"
end

Object#Tap is really simple and useful. For every object it takes block as an argument, and this block have one variable (the object itself), and whatever you do – it returns it. So, as name suggests, you can tap into any place in your method chain and inspect what is going on there. Take a look in docs example.

(*) By decent language I mean one which would allow you to introduce such feature in base Object class. In others you’re stuck with making decorators or some special objects just for that. In others maybe you have a chance, but in php you’re doomed:

Share Button

Leave a Reply

Your email address will not be published. Required fields are marked *