This is a little tune I’ve been humming a lot lately. It’s as handy as array.map(&:property). Really. You ever find yourself doing something like this?
def change_state(object_id, new_state) object = find(object_id) object.state = new_state object.save object end
Maybe not, but the pattern’s there: make an object, do something to the object, return the object. Rails’ returning method bundles this all up into joyful syntax:
def change_state(object_id, new_state) returning find(object_id) do |object| object.state = new_state object.save end end
You get the idea.
Try this one on for size (from ActionController):
def self.view_class @view_class ||= # create a new class based on the default template class and include helper methods returning Class.new(ActionView::Base) do |view_class| view_class.send(:include, master_helper_module) end end
Definitely.
update_attribute will save you another line.
This resembles let statement a bit – even javascript is going to support it: http://developer.mozilla.org/en/docs/New_in_JavaScript_1.7#Block_scope_with_let I also tend to write things like: let(v+4,x*5){|a,b| ...whatever} or quite useful Array#let ? ;) |fruit,count| do ..whetaver end
I’m fairly new to Ruby/Rails, but I’m not sure I follow your first example. How exactly is the returning syntax better than the original? It’s the same amount of lines and seems to be equivalent.
returning is cool. It’s the Ruby version of the K combinator!
I’ve used something like this for a long time (in my .irbrc file):
The original inspiration for the name “tap” (rather than use k) was from MenTaLguYs blog
Robin: I would say this is more of a conceptual win than anything. You’re able to wrap up the code which needs to modify the same temporary variable into a block. I think of it as “I want to return this object, but first…”
Ah, that does make more sense, thank you.
It’s the Ruby version of Lisp’s prog1! Which is the same thing as the K combinator! Learning new things is almost as much fun as exclamation points!
I must have missed array.map(&:property), can someone give me a link?
Can you explain this to a poor old Java programmer? Why do you have to save or return the object?
The K combinator pattern is nice, but you don’t want to use it on a performance critical path. Using local variables is much faster than returning.
BTW, I wrote the code that you cite from ActionController. It only gets executed once per view class ;-)
aadric: when Ruby sees &, it will try to call the to_proc method on something and then turn it into a block. The Symbol#to_proc method uses in Rails is a neat little trick that calls the Kernel method named ‘method’. The Ruby documentation says about ‘method’:
I hate to say it, but tricks like “&:property” start to remind me uncharitably of Perl.
Chime in.