Sha256: a5d1495e74075f4d75edc27e24fbbd9be1a2b72c63cc4d5a4442314350e59b14

Contents?: true

Size: 1.38 KB

Versions: 14

Compression:

Stored size: 1.38 KB

Contents

module Headmin
  module Sortable
    def sort(collection)
      if sort_params.to_h.any?
        sort_by_params(collection)
      elsif collection.attribute_names.include?(:created_at.to_s)
        collection.order(created_at: :desc)
      else
        collection
      end
    end

    def sort_by_params(collection)
      sort_params.each do |key, value|
        next unless %w(asc desc).include?(value)
        attribute = key.gsub('sort_', '')

        # Sort on model columns first, then check for translation columns
        if collection.attribute_names.include?(attribute.to_s)
          column = collection.arel_table[attribute]
        elsif collection.respond_to?(:translation_class) && collection.translation_class.attribute_names.include?(attribute.to_s)
          column = collection.translation_class.arel_table[attribute]
        else
          next
        end

        order_scope = "order_by_#{attribute}".to_sym
        sort_scope = "sort_by_#{attribute}".to_sym
        if collection.respond_to?(order_scope)
          collection = collection.send(order_scope, value)
        elsif collection.respond_to?(sort_scope)
          collection = collection.send(sort_scope, value)
        else
          collection = collection.order(column.send(value))
        end
      end
      collection
    end

    def sort_params
      params.permit!.select { |p| p.to_s.include?('sort_') }
    end
  end
end

Version data entries

14 entries across 14 versions & 1 rubygems

Version Path
headmin-0.2.9 app/controllers/concerns/headmin/sortable.rb
headmin-0.3.2 app/controllers/concerns/headmin/sortable.rb
headmin-0.3.1 app/controllers/concerns/headmin/sortable.rb
headmin-0.2.8 app/controllers/concerns/headmin/sortable.rb
headmin-0.2.7 app/controllers/concerns/headmin/sortable.rb
headmin-0.2.6 app/controllers/concerns/headmin/sortable.rb
headmin-0.2.5 app/controllers/concerns/headmin/sortable.rb
headmin-0.2.4 app/controllers/concerns/headmin/sortable.rb
headmin-0.2.3 app/controllers/concerns/headmin/sortable.rb
headmin-0.2.2 app/controllers/concerns/headmin/sortable.rb
headmin-0.2.1 app/controllers/concerns/headmin/sortable.rb
headmin-0.2.0 app/controllers/concerns/headmin/sortable.rb
headmin-0.1.2 app/controllers/concerns/headmin/sortable.rb
headmin-0.1.1 app/controllers/concerns/headmin/sortable.rb