Module: NiftyScope::ClassMethods

Defined in:
lib/nifty_scope.rb

Instance Method Summary collapse

Instance Method Details

#nifty_scope(params, options = {}) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/nifty_scope.rb', line 7

def nifty_scope(params, options = {})
  if options.has_key?(:only)
    options[:only] = Array(options[:only])
    params.slice!(*options[:only])
  elsif options.has_key?(:except)
    options[:except] = Array(options[:except])
    params.except!(*options[:except])
  end

  mapping ||= options[:mapping] || {}
  scope = where(nil)

  params.each do |(key, value)|
    key = key.to_sym
    scope_method = if mapping.has_key?(key)
      mapping[key]
    else
      key
    end
    if scope_method.is_a?(Symbol) && !scope.respond_to?(scope_method)
      raise IrresponsibleScope, "#{scope.name} can't respond to ##{scope_method} method"
    end

    scope = if scope_method.is_a?(Proc)
      scope.instance_exec(value, &scope_method)
    else
      scope.send(scope_method, value)
    end
  end
  scope
end