Module: Enumerable
- Defined in:
- lib/enumerable_mapper.rb
Defined Under Namespace
Classes: Mapper
Instance Method Summary collapse
-
#grouped_by(method_id = nil) ⇒ Object
Group collection according to the method name or block given.
-
#mapped ⇒ Object
(also: #collected)
Returns a new mapper for the collection.
Instance Method Details
#grouped_by(method_id = nil) ⇒ Object
Group collection according to the method name or block given.
Examples:
Person.find( :all ).grouped_by( :company )
Person.find( :all ).grouped_by{ |p| p.born_on.year }
28 29 30 31 32 |
# File 'lib/enumerable_mapper.rb', line 28 def grouped_by( method_id=nil ) raise "No method or block given" unless method_id or block_given? groupings = self.map{ |i| ( block_given? ) ? yield( i ) : i.send( method_id ) }.uniq groupings.map{ |g| [ g, self.select{ |i| ( ( block_given? ) ? yield( i ) : i.send( method_id ) ) == g } ] } end |