#6
Mar 16, 2007

Shortcut Blocks with Symbol to_proc

It may have a goofy syntax, but the Symbol#to_proc feature Rails adds allows you to do simple blocks very quickly and easily.
Download (6.5 MB, 3:44)
alternative download for iPod & Apple TV (4.9 MB, 3:44)
# models/task.rb
def self.all_names
  find(:all).collect(&:name)
end

RSS Feed for Episode Comments 6 comments

1. Frank Jul 09, 2007 at 09:30

Maybe a stupid question but is it possible to use Symbol to_proc even for methods which need an argument?


2. Ryan Bates Jul 09, 2007 at 09:32

Nope, it only works on very simple method calls which don't take an argument. Anything more complicated and you will need to use the full block.


3. Mike Stramba Jul 11, 2007 at 11:27

Ryan,

Can more than one attribute be combined / concatenated ?

e.g. :
Something like ... (this doesn't work) :

ActorNames = Actor.find(:all).collect(&:last_name + ' ' + &:first_name)

.. neither does :

ActorNames = Actor.find(:all).collect(&:last_name,&:first_name)

Mike


4. Ryan Bates Jul 11, 2007 at 12:10

@Mike, nope, you can only call a single method with Symbol to_proc. If you want to combine two methods like you're trying to do, I recommend creating a new "full_name" method in the actor model to do this. That way you're back to calling one method.


5. Bobby Digital Jul 25, 2007 at 00:53

Before your readers subscribe to this method, they should be aware of the performance issue.

http://m.onkey.org/2007/6/30/let-s-start-with-wtf

Apparently, nothing beats a good olf-fashioned block


6. kino May 23, 2008 at 01:53

By virtue of my free epoche with respect to the being of the experienced world, the momentous fact is that we must not let ourselves be frightened by considerations of the ego cogito and cogitationes.

Add your comment:

(SKIP THIS ONE)

(required)

(not shown)


(use pastie or gist for code)

sponsored by:
if you want to help:
required:
Get Quicktime Player