Sha256: d62b4ddf92832f434a06fbc1a4081a5dcd982fb254a4246c7b8df6a788b74bae

Contents?: true

Size: 846 Bytes

Versions: 7

Compression:

Stored size: 846 Bytes

Contents

# frozen_string_literal: true

require_relative 'sort/direction'

module Realize
  class Collection
    # Transformer to take an array of objects and sort by the given key
    # and by the given sort direction. Defaulting to ascending.
    class Sort
      include Arrays
      include Direction
      acts_as_hashable

      DEFAULT_ORDER = ASCENDING

      attr_reader :key, :order

      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

      def transform(resolver, value, _time, _record)
        records = array(value)

        sorted = records.sort_by { |hsh| resolver.get(hsh, key) }

        order == DESCENDING ? sorted.reverse : sorted
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
realize-1.3.0 lib/realize/collection/sort.rb
realize-1.2.0 lib/realize/collection/sort.rb
realize-1.2.0.pre.alpha lib/realize/collection/sort.rb
realize-1.1.1 lib/realize/collection/sort.rb
realize-1.1.1.pre.alpha lib/realize/collection/sort.rb
realize-1.1.0 lib/realize/collection/sort.rb
realize-1.0.0 lib/realize/collection/sort.rb