Ruby Class to_proc

A couple of the reasons I like Rails' Symbol#to_proc is because it saves keystrokes and looks nicer.

I would much rather write:
[...].map(&:name)
than:
[...].map { |x| x.name }

I noticed in _why's post today that the Method class has a to_proc method. This is useful when you want to pass an array of values to a method individually. Instead of:
%w[mocha heckle].each { |g| gem g }
You can write:
%w[mocha heckle].each(&method(:gem))

This gave me the idea to try this with instantiating classes. To map an array of attributes into instantiated ActiveRecord models, this works:
class Person < ActiveRecord::Base; end;
[{:name => 'Dan'}, {:name => 'Josh'}].map(&Person.method(:new))

However, calling new may be common enough to be default behavior as Class#to_proc.
class Class
  def to_proc
    proc(&method(:new))
  end
end

Now the above line of code becomes:
[{:name => 'Dan'}, {:name => 'Josh'}].map(&Person)

For a slightly more real-world example, it's sometimes useful to wrap an ActiveRecord model in a presenter:
Person.find(1,2,3).map(&PersonPresenter)
I think that's pretty clean, and I like it better than:
Person.find(1,2,3).map { |p| PersonPresenter.new(p) }
Hi, I'm Dan Manges, a software developer best known for being the founding CTO of Braintree. Send me an email.
blog comments powered by Disqus