Class: Toller::Filter

Inherits:
Object
  • Object
show all
Defined in:
lib/toller/filter.rb

Overview

Filter

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(parameter, type, options) ⇒ Toller::Filter

Returns a new instance of Filter.

Parameters:

  • parameter (Symbol)

    the public filter param name

  • type (Symbol)

    the filter type, e.g. :string, :integer, :scope

  • options (Hash)

    filter options; merged over defaults for :field, :default, and :scope_name

Options Hash (options):

  • :field (Symbol)

    the column/attribute to query; defaults to parameter

  • :default (Boolean)

    whether this filter applies automatically when no filter params were sent

  • :scope_name (Symbol)

    for type: :scope, the model scope to call; defaults to parameter



24
25
26
27
28
29
30
31
32
# File 'lib/toller/filter.rb', line 24

def initialize(parameter, type, options)
  @parameter = parameter
  @type = type
  @properties = options.reverse_merge(
    field: parameter,
    default: false,
    scope_name: nil
  )
end

Instance Attribute Details

#parameterSymbol (readonly)

Returns the public filter param name.

Returns:

  • (Symbol)

    the public filter param name



8
9
10
# File 'lib/toller/filter.rb', line 8

def parameter
  @parameter
end

#propertiesHash (readonly)

Returns the filter's resolved options (:field, :default, :scope_name, etc.).

Returns:

  • (Hash)

    the filter's resolved options (:field, :default, :scope_name, etc.)



11
12
13
# File 'lib/toller/filter.rb', line 11

def properties
  @properties
end

#typeSymbol (readonly)

Returns the filter type, e.g. :string, :integer, :scope.

Returns:

  • (Symbol)

    the filter type, e.g. :string, :integer, :scope



14
15
16
# File 'lib/toller/filter.rb', line 14

def type
  @type
end

Instance Method Details

#apply!(collection, value) ⇒ ActiveRecord::Relation

Applies this filter to collection, dispatching to the scope or where handler based on type.

Parameters:

  • collection (ActiveRecord::Relation)

    the collection to filter

  • value (Object)

    the active filter param value

Returns:

  • (ActiveRecord::Relation)

    the filtered collection



41
42
43
44
45
46
47
# File 'lib/toller/filter.rb', line 41

def apply!(collection, value)
  if type == :scope
    Filters::ScopeHandler.new.call(collection, value, properties)
  else
    Filters::ColumnHandler.new.call(collection, type, value, properties)
  end
end

#defaultBoolean

Returns whether this filter applies automatically when no filter params were sent at all.

Returns:

  • (Boolean)

    whether this filter applies automatically when no filter params were sent at all



51
52
53
# File 'lib/toller/filter.rb', line 51

def default
  properties[:default]
end