Class: Doure::Filter
- Inherits:
-
Object
- Object
- Doure::Filter
- Defined in:
- lib/doure/filter.rb
Constant Summary collapse
- VALID_CASTINGS =
%i(boolean date datetime)
- InvalidCasting =
Class.new(StandardError)
Class Method Summary collapse
- .cont_filter(name, opts = {}) ⇒ Object
- .eq_filter(name, opts = {}) ⇒ Object
- .filter(name, opts = {}, &apply) ⇒ Object
- .inherited(subclass) ⇒ Object
- .not_eq_filter(name, opts = {}) ⇒ Object
- .present_filter(name, opts = {}) ⇒ Object
Instance Method Summary collapse
- #apply(params = {}) ⇒ Object
-
#initialize(scope) ⇒ Filter
constructor
A new instance of Filter.
Constructor Details
#initialize(scope) ⇒ Filter
Returns a new instance of Filter.
47 48 49 |
# File 'lib/doure/filter.rb', line 47 def initialize(scope) @scope = scope.all # Force AR:Relation from possible AR:Base end |
Class Method Details
.cont_filter(name, opts = {}) ⇒ Object
29 30 31 32 |
# File 'lib/doure/filter.rb', line 29 def cont_filter(name, opts = {}) block = lambda { |s, value| s.where(s.arel_table[name].matches("%#{value}%")) } mapping["#{name}_cont"] = [opts, block] end |
.eq_filter(name, opts = {}) ⇒ Object
19 20 21 22 |
# File 'lib/doure/filter.rb', line 19 def eq_filter(name, opts = {}) block = lambda { |s, value| s.where(name => value) } mapping["#{name}_eq"] = [opts, block] end |
.filter(name, opts = {}, &apply) ⇒ Object
15 16 17 |
# File 'lib/doure/filter.rb', line 15 def filter(name, opts = {}, &apply) mapping[name] = [opts, apply] end |
.inherited(subclass) ⇒ Object
11 12 13 |
# File 'lib/doure/filter.rb', line 11 def inherited(subclass) subclass.mapping = self.mapping.dup end |
.not_eq_filter(name, opts = {}) ⇒ Object
24 25 26 27 |
# File 'lib/doure/filter.rb', line 24 def not_eq_filter(name, opts = {}) block = lambda { |s, value| s.where.not(name => value) } mapping["#{name}_not_eq"] = [opts, block] end |
.present_filter(name, opts = {}) ⇒ Object
34 35 36 37 |
# File 'lib/doure/filter.rb', line 34 def present_filter(name, opts = {}) block = lambda { |s, value| value ? s.where.not(name => nil) : s.where(name => nil) } mapping["#{name}_present"] = [opts.merge(as: :boolean), block] end |
Instance Method Details
#apply(params = {}) ⇒ Object
51 52 53 54 55 56 57 58 59 |
# File 'lib/doure/filter.rb', line 51 def apply(params = {}) params.each do |key, value| if !value.nil? && value != "" && mapping.key?(key) @scope = instance_exec(@scope, cast_value(mapping[key][0], value), &mapping[key][1]) end end @scope end |