Sha256: ba77bd7497630804c8c9649c81d06c9bcfa7f02a387e4d052dd6891de887ad03

Contents?: true

Size: 1.38 KB

Versions: 2

Compression:

Stored size: 1.38 KB

Contents

module SearchObject
  module Plugin
    module Sorting
      def self.included(base)
        base.extend ClassMethods
        base.instance_eval do
          option :sort do |scope, _|
            scope.order "#{sort_attribute} #{sort_direction}"
          end
        end
      end

      def sort?(attribute)
        attribute == sort || sort.to_s.starts_with?("#{attribute} ")
      end

      def sort_attribute
        @sort_attribute ||= Helper.ensure_included sort.to_s.split(' ', 2).first, self.class.sort_attributes
      end

      def sort_direction
        @sort_direction ||= Helper.ensure_included sort.to_s.split(' ', 2).last, %w(desc asc)
      end

      def sort_direction_for(attribute)
        if sort_attribute == attribute.to_s
          reverted_sort_direction
        else
          'desc'
        end
      end

      def sort_params_for(attribute, options = {})
        options['sort'] = "#{attribute} #{sort_direction_for(attribute)}"
        params options
      end

      def reverted_sort_direction
        sort_direction == 'desc' ? 'asc' : 'desc'
      end

      module ClassMethods
        def sort_by(*attributes)
          config[:sort_attributes]  = attributes.map(&:to_s)
          config[:defaults]['sort'] = "#{config[:sort_attributes].first} desc"
        end

        def sort_attributes
          config[:sort_attributes] ||= []
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
search_object-1.1.1 lib/search_object/plugin/sorting.rb
search_object-1.1.0 lib/search_object/plugin/sorting.rb