Class: Filtered::Base

Inherits:
Object
  • Object
show all
Extended by:
ClassMethods
Includes:
InstanceMehods
Defined in:
lib/filtered/base.rb

Direct Known Subclasses

ApplicationFilter

Defined Under Namespace

Modules: ClassMethods, InstanceMehods

Class Method Summary collapse

Instance Method Summary collapse

Methods included from ClassMethods

field, field_definitions

Constructor Details

#initialize(params = {}) {|_self| ... } ⇒ Base

Initializes a new filter with the given params.

 class CarFilter < ApplicationFilter

   attr_accessor :user

   field :year, allow_blank: true do |value, filter|
     -> { where(year: value, user: filter.user) }
   end

   field :make
   field :model
   field :body

 end

 class NoiseMeasurementsController < ApplicationController
   before_action :set_filter

   def index
     @measurements = CarNoiseMeasurement.all.merge(@filter)
   end

   private

   def set_filter
     @filter = CarsFilter.new(filter_params) do |f|
      f.user = current_user
     end
   end

   def filter_params
     params.fetch(:filter, {}).permit(make: [], model: [], year: [], body: [])
   end
end

Yields:

  • (_self)

Yield Parameters:



181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# File 'lib/filtered/base.rb', line 181

def initialize(params = {}, &block)
  params.each do |name, value|
    name = name.to_sym

    raise Error, "Passing '#{name}' filter which is not defined" unless fields.defined?(name)

    fields[name] = value
  end

  yield self if block_given?

  fields.each do |name, value, definition|
    next if value || !definition.default_computer

    fields[name] = definition.default_computer.(self)
  end
end

Class Method Details

.inherited(base) ⇒ Object



133
134
135
136
137
138
139
140
141
142
143
# File 'lib/filtered/base.rb', line 133

def self.inherited(base)
  base.instance_variable_set(:"@field_definitions", Hash.new)

  if field_definitions
    field_definitions.each do |(name, definition)|
      base.field_definitions[name] = definition
    end
  end

  super
end

Instance Method Details

#inspectObject



218
219
220
221
222
# File 'lib/filtered/base.rb', line 218

def inspect
  inspection = entitled_fields.collect { |name, value| "#{name}: #{value.inspect}" }.compact.join(", ")

  "#<#{self.class} #{inspection}>"
end

#to_hashObject



214
215
216
# File 'lib/filtered/base.rb', line 214

def to_hash
  Hash[entitled_fields.map { |name, value| [name, value] }]
end

#to_procObject

ActiveRecord calls to_proc when filter merged into relation.



201
202
203
204
205
206
207
208
209
210
211
212
# File 'lib/filtered/base.rb', line 201

def to_proc
  procs = entitled_fields.inject([]) do |memo, (name, value, definition)|
    memo << eval_option_proc(definition.query_updater, value)

    memo
  end

  ->() {
    # here self is an ActiveRecord relation
    procs.inject(self) { |chain, next_proc| chain.merge(next_proc) }
  }
end