map_by_method now works with ActiveRecord associations
I was always annoyed that map_by_method
was broken for ActiveRecord has_many
associations. 6 mths later I finally fixed it.
That’s the magic of Open Source Software. [/end sarcasm]
So now, the following example works like it should:
$ gem install map_by_method $ console > require 'map_by_method' # stick this in your environment.rb for Rails > user = User.find_by_name "Dr Nic" > user.companies.map_by_name => ['Dr Nic Academy', 'Dr Nic Institute of Being Silly'] > user.companies.map_by_id_and_name => [[1, 'Dr Nic Academy'], [9, 'Dr Nic Institute of Being Silly']]
Recap: why use map_by_method
?
Try the following example:
> user.companies.map_by_employees.flatten => list of all employees of user
Versus:
> user.companies.map { |company| company.employees}.flatten or > user.companies.map(&:employees).flatten
Or compare:
> user.companies.map_by_id_and_name => [[1, 'Dr Nic Academy'], [9, 'Dr Nic Institute of Being Silly']]
Versus:
> user.companies.map { |company| [company.id, company.name]}
That is, it looks and feels just like ActiveRecord’s #find method, with its find_by_first_name_and_last_name
magic.
Summary
No {
, }
, |
, &
, or :
required. Just clean method names.
Bonus other gem
In the spirit of ActiveRecord hacks, there is to_activerecord
:
$ gem install to_activerecord $ console > require 'to_activerecord' # stick this in your environment.rb for Rails > [1,2,3].to_user => [list of User with id's 1,2,3]
To me, this suffix operator reads cleaner than the traditional:
> User.find([1,2,3])
For example, if you want to perform an operation on the list of Users:
> ids = [1,2,3] > ids.to_user.map_by_name => ['Dr Nic', 'Banjo', 'Nancy']
Versus:
> User.find(ids).map_by_name
No comments:
Post a Comment