Module: Mongoid::Listable::Extensions::Array

Defined in:
lib/mongoid/listable/extensions/array.rb

Instance Method Summary collapse

Instance Method Details

#sort_by_attr(k, v) ⇒ Object

Sorts an array of objects on the specified key, sorted by the order of the key in an array. Example:

[‘Richard’,

{name: 'Ashley'}, 
{name: 'Chris'}].sort_by_attr(:name, ['Chris', 'Richard', 'Ashley'])

> [‘Chris’, ‘Richard’, ‘Ashley’]

Since:

  • 0.0.6



22
23
24
25
# File 'lib/mongoid/listable/extensions/array.rb', line 22

def sort_by_attr k, v
  v.reject! &:blank?
  sort { |a, b| v.index(a.send(k)) <=> v.index(b.send(k)) }
end