Class: Paraphrase::ScopeMapping
- Inherits:
-
Object
- Object
- Paraphrase::ScopeMapping
- Defined in:
- lib/paraphrase/scope_mapping.rb
Instance Attribute Summary collapse
-
#keys ⇒ Array<Symbol>
readonly
Param keys to extract.
-
#method_name ⇒ Symbol
readonly
Scope name.
-
#required ⇒ Array
readonly
Keys required for query.
-
#whitelist ⇒ Object
readonly
Returns the value of attribute whitelist.
Instance Method Summary collapse
-
#chain(params, relation) ⇒ ActiveRecord::Relation
Sends #method_name to
chain, extracting arguments fromparams. -
#initialize(name, options) ⇒ ScopeMapping
constructor
A new instance of ScopeMapping.
Constructor Details
#initialize(name, options) ⇒ ScopeMapping
Returns a new instance of ScopeMapping.
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/paraphrase/scope_mapping.rb', line 25 def initialize(name, ) @method_name = name @keys = Array(.delete(:to)) @required = register_keys([:require]) @whitelist = register_keys([:whitelist]) if @whitelist.empty? && !@required.empty? @whitelist = @keys - @required end if (whitelist & required).any? raise ArgumentError, "cannot whitelist and require the same keys" end end |
Instance Attribute Details
#keys ⇒ Array<Symbol> (readonly)
Returns param keys to extract.
16 17 18 |
# File 'lib/paraphrase/scope_mapping.rb', line 16 def keys @keys end |
#method_name ⇒ Symbol (readonly)
Returns scope name.
16 |
# File 'lib/paraphrase/scope_mapping.rb', line 16 attr_reader :keys, :method_name, :required, :whitelist |
#required ⇒ Array (readonly)
Returns keys required for query.
16 |
# File 'lib/paraphrase/scope_mapping.rb', line 16 attr_reader :keys, :method_name, :required, :whitelist |
#whitelist ⇒ Object (readonly)
Returns the value of attribute whitelist.
16 |
# File 'lib/paraphrase/scope_mapping.rb', line 16 attr_reader :keys, :method_name, :required, :whitelist |
Instance Method Details
#chain(params, relation) ⇒ ActiveRecord::Relation
Sends #method_name to chain, extracting arguments from params. If
values are missing for any #keys, return the chain unmodified.
If required, errors are added to the Query instance as
well.
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
# File 'lib/paraphrase/scope_mapping.rb', line 49 def chain(params, relation) scope = relation.respond_to?(:klass) ? relation.klass.method(method_name) : relation.method(method_name) inputs = keys.map do |key| input = params[key] if input.nil? break if required.include?(key) break [] if !whitelist.include?(key) end input end if inputs.nil? return elsif inputs.empty? return relation end scope.arity == 0 ? relation.send(method_name) : relation.send(method_name, *inputs) end |