Module: ActiveRecord::FilterableBy

Defined in:
lib/filterable_by.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Class Method Details

.merge(scope, unscoped, hash, name, **opts, &block) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/filterable_by.rb', line 16

def self.merge(scope, unscoped, hash, name, **opts, &block)
  key = name
  positive = normalize(hash[key]) if hash.key?(key)
  if positive.present?
    sub = block.arity == 2 ? yield(unscoped, positive, **opts) : yield(positive, **opts)
    return nil unless sub

    scope = scope.merge(sub)
  end

  key = "#{name}_not"
  negative = normalize(hash[key]) if hash.key?(key)
  if negative.present?
    sub = block.arity == 2 ? yield(unscoped, negative, **opts) : yield(negative, **opts)
    return nil unless sub

    if sub.respond_to?(:invert_where)
      sub = sub.invert_where
    else
      sub.where_clause = sub.where_clause.invert
    end
    scope = scope.merge(sub)
  end

  scope
end

.normalize(value) ⇒ Object



7
8
9
10
11
12
13
14
# File 'lib/filterable_by.rb', line 7

def self.normalize(value)
  case value
  when String, Numeric
    value
  when Array
    value.select {|v| normalize(v) }
  end
end