class Brita::Filtrator
Filtrator
takes a collection, params and a set of filters and applies them to create a new active record collection with those filters applied.
Attributes
collection[R]
filters[R]
params[R]
sort[R]
Public Class Methods
filter(collection, params, filters, sort = [])
click to toggle source
# File lib/brita/filtrator.rb, line 8 def self.filter(collection, params, filters, sort = []) new(collection, params, sort, filters).filter end
new(collection, params, _sort, filters = [])
click to toggle source
# File lib/brita/filtrator.rb, line 12 def initialize(collection, params, _sort, filters = []) @collection = collection @params = params @filters = filters @sort = params.fetch(:sort, "").split(",") if filters.any? { |filter| filter.is_a?(Sort) } end
Public Instance Methods
filter()
click to toggle source
# File lib/brita/filtrator.rb, line 19 def filter active_filters.reduce(collection) do |col, filter| apply(col, filter) end end
Private Instance Methods
active_filters()
click to toggle source
# File lib/brita/filtrator.rb, line 47 def active_filters filters.select do |filter| filter_params[filter.param].present? || filter.default || filter.always_active? end end
active_sorts_hash()
click to toggle source
# File lib/brita/filtrator.rb, line 35 def active_sorts_hash active_sorts_hash = {} Array(sort).each do |s| if s.starts_with?("-") active_sorts_hash[s[1..-1].to_sym] = :desc else active_sorts_hash[s.to_sym] = :asc end end active_sorts_hash end
apply(collection, filter)
click to toggle source
# File lib/brita/filtrator.rb, line 27 def apply(collection, filter) filter.apply!(collection, value: filter_params[filter.param], active_sorts_hash: active_sorts_hash, params: params) end
filter_params()
click to toggle source
# File lib/brita/filtrator.rb, line 31 def filter_params params.fetch(:filters, {}) end