Sha256: 4ce5e616065ab6ba2d4bc44d96f112343e30be09ddcfe2b8090bdc310d51e842

Contents?: true

Size: 1014 Bytes

Versions: 31

Compression:

Stored size: 1014 Bytes

Contents

module Spree
  class BaseSorter
    def initialize(scope, params = {}, allowed_sort_attributes = [])
      @scope = scope
      @allowed_sort_attributes = allowed_sort_attributes
      @sort = sort_fields(params[:sort])
    end

    def call
      by_param_attributes(scope)
    end

    protected

    attr_reader :scope, :collection, :sort, :allowed_sort_attributes

    def by_param_attributes(scope)
      return scope if sort.empty?

      sort.each do |value, order|
        next if value.blank? || allowed_sort_attributes.exclude?(value.to_sym)

        scope = scope.order("#{value}": order)
      end

      scope
    end

    def sort_fields(sort)
      return [] if sort.nil?

      sort.split(',').map { |field| [sort_field(field), order_direction(field)] }
    end

    def desc_order(field)
      String(field)[0] == '-'
    end

    def sort_field(field)
      desc_order(field) ? field[1..-1] : field
    end

    def order_direction(field)
      desc_order(field) ? :desc : :asc
    end
  end
end

Version data entries

31 entries across 31 versions & 1 rubygems

Version Path
spree_core-4.10.1 app/sorters/spree/base_sorter.rb
spree_core-4.10.0 app/sorters/spree/base_sorter.rb
spree_core-4.9.0 app/sorters/spree/base_sorter.rb
spree_core-4.8.3 app/sorters/spree/base_sorter.rb
spree_core-4.8.2 app/sorters/spree/base_sorter.rb
spree_core-4.7.3 app/sorters/spree/base_sorter.rb
spree_core-4.6.6 app/sorters/spree/base_sorter.rb
spree_core-4.5.5 app/sorters/spree/base_sorter.rb
spree_core-4.3.3 app/sorters/spree/base_sorter.rb
spree_core-4.4.1 app/sorters/spree/base_sorter.rb
spree_core-4.5.4 app/sorters/spree/base_sorter.rb
spree_core-4.6.5 app/sorters/spree/base_sorter.rb
spree_core-4.7.2 app/sorters/spree/base_sorter.rb
spree_core-4.7.1 app/sorters/spree/base_sorter.rb
spree_core-4.6.4 app/sorters/spree/base_sorter.rb
spree_core-4.7.0 app/sorters/spree/base_sorter.rb
spree_core-4.6.3 app/sorters/spree/base_sorter.rb
spree_core-4.6.2 app/sorters/spree/base_sorter.rb
spree_core-4.6.1 app/sorters/spree/base_sorter.rb
spree_core-4.6.0 app/sorters/spree/base_sorter.rb