Class: Realize::Collection::Sort

Inherits:
Object
  • Object
show all
Includes:
Arrays, Direction
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

Instance Method Summary collapse

Methods included from Arrays

#array

Constructor Details

#initialize(key:, order: DEFAULT_ORDER) ⇒ Sort

Returns a new instance of Sort.

Raises:

  • (ArgumentError)


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

#keyObject (readonly)

Returns the value of attribute key.



23
24
25
# File 'lib/realize/collection/sort.rb', line 23

def key
  @key
end

#orderObject (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