Class: Realize::Collection::Sort
- Inherits:
-
Object
- Object
- Realize::Collection::Sort
- Defined in:
- lib/realize/collection/sort.rb,
lib/realize/collection/sort/direction.rb
Overview
Transformer to take an array of objects and sort by the given key and by the given sort direction. Defaulting to ascending.
Defined Under Namespace
Modules: Direction
Constant Summary collapse
- DEFAULT_ORDER =
ASCENDING
Constants included from Direction
Direction::ASCENDING, Direction::DESCENDING
Instance Attribute Summary collapse
-
#key ⇒ Object
readonly
Returns the value of attribute key.
-
#order ⇒ Object
readonly
Returns the value of attribute order.
Instance Method Summary collapse
-
#initialize(key:, order: DEFAULT_ORDER) ⇒ Sort
constructor
A new instance of Sort.
- #transform(resolver, value, _time, _record) ⇒ Object
Methods included from Arrays
Constructor Details
#initialize(key:, order: DEFAULT_ORDER) ⇒ Sort
Returns a new instance of Sort.
25 26 27 28 29 30 31 32 |
# File 'lib/realize/collection/sort.rb', line 25 def initialize(key:, order: DEFAULT_ORDER) raise ArgumentError, 'key is required' if key.to_s.empty? @key = key @order = Direction.const_get(order.to_s.upcase.to_sym) freeze end |
Instance Attribute Details
#key ⇒ Object (readonly)
Returns the value of attribute key.
23 24 25 |
# File 'lib/realize/collection/sort.rb', line 23 def key @key end |
#order ⇒ Object (readonly)
Returns the value of attribute order.
23 24 25 |
# File 'lib/realize/collection/sort.rb', line 23 def order @order end |
Instance Method Details
#transform(resolver, value, _time, _record) ⇒ Object
34 35 36 37 38 39 40 |
# File 'lib/realize/collection/sort.rb', line 34 def transform(resolver, value, _time, _record) records = array(value) sorted = records.sort_by { |hsh| resolver.get(hsh, key) } order == DESCENDING ? sorted.reverse : sorted end |