Sha256: 182d44773047a01c7813c92fca401cc7e90abb4c3a47c706e754e799038f728d

Contents?: true

Size: 1.31 KB

Versions: 9

Compression:

Stored size: 1.31 KB

Contents

module Headmin
  class Filters
    # Example:
    #
    # @orders = Headmin::Filters.new(params, {
    #   status: :text,
    #   price: :number,
    #   in_stock: :boolean
    # }).query(Order)

    def initialize(params, param_types)
      @params = params
      @param_types = param_types
    end

    def parse(attribute, type, association: nil)
      class_name = "Headmin::Filter::#{type.to_s.classify}".constantize
      class_name.new(attribute, @params, association: association)
    end

    def query(collection)
      @param_types.each do |attribute, type|
        if type.is_a? Hash
          # We are given attribute filters of an association
          association = attribute

          # By default, we offer a filter of type association
          association_filter = Headmin::Filter::Association.new(attribute, @params, association: nil)
          collection = association_filter.query(collection)

          # Query all the passed attribute filters for this association
          type.each do |new_attribute, new_type|
            filter = parse(new_attribute, new_type, association: association)
            collection = filter.query(collection)
          end
        else
          filter = parse(attribute, type)
          collection = filter.query(collection)
        end
      end
      collection
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
headmin-0.6.3 app/models/headmin/filters.rb
headmin-0.6.2 app/models/headmin/filters.rb
headmin-0.6.1 app/models/headmin/filters.rb
headmin-0.6.0 app/models/headmin/filters.rb
headmin-0.5.9 app/models/headmin/filters.rb
headmin-0.5.8 app/models/headmin/filters.rb
headmin-0.5.7 app/models/headmin/filters.rb
headmin-0.5.6 app/models/headmin/filters.rb
headmin-0.5.5 app/models/headmin/filters.rb