Sha256: 902e956f8b9e132c6d33090acbf363234c3e3c8114cc5080447812d256bfb0c2

Contents?: true

Size: 1.04 KB

Versions: 14

Compression:

Stored size: 1.04 KB

Contents

# frozen_string_literal: true

require_relative '../base_adapter'
require_relative '../base_processor'

class ActiveSet
  class SortProcessor < BaseProcessor
    class EnumerableAdapter < BaseAdapter
      def process
        return_set(sorted_set)
      end

      private

      def sorted_set
        @set.sort_by { |item| sortable_attribute_for(item: item) }
            .tap { |c| c.reverse! if descending? }
      end

      def sortable_attribute_for(item:)
        attribute_value = @instruction.value_for(item: item)
        case_insensitive?(attribute_value) ? insensify(attribute_value) : attribute_value
      end

      def case_insensitive?(value)
        # Cannot sort pure Booleans or Nils, so we _must_ cast to Strings
        return true if value.is_a?(TrueClass) || value.is_a?(FalseClass)
        return true if value.is_a?(NilClass)
        @instruction.operator.to_s == 'i'
      end

      def insensify(value)
        value.to_s.downcase
      end

      def descending?
        @instruction.value.to_s == 'desc'
      end
    end
  end
end

Version data entries

14 entries across 14 versions & 1 rubygems

Version Path
activeset-0.5.8 lib/active_set/processors/sort/enumerable_adapter.rb
activeset-0.5.7 lib/active_set/processors/sort/enumerable_adapter.rb
activeset-0.5.6 lib/active_set/processors/sort/enumerable_adapter.rb
activeset-0.5.5 lib/active_set/processors/sort/enumerable_adapter.rb
activeset-0.5.4 lib/active_set/processors/sort/enumerable_adapter.rb
activeset-0.5.3 lib/active_set/processors/sort/enumerable_adapter.rb
activeset-0.5.2 lib/active_set/processors/sort/enumerable_adapter.rb
activeset-0.5.1 lib/active_set/processors/sort/enumerable_adapter.rb
activeset-0.5.0 lib/active_set/processors/sort/enumerable_adapter.rb
activeset-0.4.4 lib/active_set/processors/sort/enumerable_adapter.rb
activeset-0.4.3 lib/active_set/processors/sort/enumerable_adapter.rb
activeset-0.4.2 lib/active_set/processors/sort/enumerable_adapter.rb
activeset-0.4.1 lib/active_set/processors/sort/enumerable_adapter.rb
activeset-0.4.0 lib/active_set/processors/sort/enumerable_adapter.rb