13 Aug, 2007

Published at 05:02AM

Tagged with gems, programming, rails, and reference

This post has 0 comments

map_by_method gem

map_by_method is a gem for Rails that provides a little more readability than inline blocks and Symbol#to_proc. Compare the following (from the source):

1
2
3
4
5
6
7
8
# inline block... not bad.
user.companies.map { |company| company.employees }.flatten

# Symbol#to_proc... much better.
user.companies.map(&:employees).flatten

# map_by_method... perfect.
user.companies.map_by_employees.flatten

Part of me still likes Symbol#to_proc, but here’s where it gets better. map_by_method works like the Rails dynamic finders. Since you can only use Symbol#to_proc when you’re mapping one attribute, you’re left with inline blocks otherwise. While that’s still not bad, an arguably more readable option is to use the map_by_method dynamic mapping. For instance…

1
2
3
4
5
# inline block for multiple columns
automobile.cars.map { |car| [car.year, car.make, car.model] }.flatten

# dynamic mapping
automobile.cars.map_by_year_and_make_and_model.flatten

Good stuff.

Comments

Do you have something to say about this post?
Retype the image to the right Spam Hint: Are You Human? Textile Formatting Tips

or

Ryan Heath | Site Management A Ruby on Rails production.

This site is a Formed Function. Formed Function LLC | @formedfunction | Get in Touch