Class: DynamicScope::Processor
- Inherits:
-
Object
- Object
- DynamicScope::Processor
- Defined in:
- lib/dynamic_scope/processor.rb
Overview
Processor for dynamic scope.
usage:
params =
'0' => {key: 'id', operator: 'eq', value: '1',
}
config = {
id: {type: :integer}
} processor = DynamicScope::Processor.new(Model.all, params, config) Model.all.merge(processor.scope)
Config format: {
key: {
# Required
type: :integer || :string || :enum || :datetime,
# Required for type :enum
values: ['value_1', 'value_2'],
# Optional: uses key OR given value to determine which scope to call
# scope receives (operator, value) as arguments.
scope: true || :some_scope_name,
# Opional: adds "OR :attribute IS NULL" to SQL statement
# when operator is negative.
null: true,
# Optional: uses given value if attribute_name differs from key
attribute_name: :some_column,
# Optional: use when attribute resides in some other model,
# uses rails relations to generate joins.
# If given, the scope option affects this class.
relation: :parent_model,
relation: {parent_model: :granparent_model},
# Optional: use to modify value coming from params
value: lambda{|value| "#{value}"}
}
Params format: {
'0' => {
# Required: hash key of config
key: 'key',
# Required:
# Supported operators are defined in DynamicScope::Query::OPERATORS
operator: 'operator',
# Required:
value: 'value'
# Opional: adds "OR :attribute IS NULL" to SQL statement
null: true,
}
}
Instance Attribute Summary collapse
-
#config ⇒ Object
readonly
Returns the value of attribute config.
-
#params ⇒ Object
readonly
Returns the value of attribute params.
Instance Method Summary collapse
-
#initialize(scope, params, config) ⇒ Processor
constructor
A new instance of Processor.
- #scope ⇒ Object
Constructor Details
#initialize(scope, params, config) ⇒ Processor
Returns a new instance of Processor.
68 69 70 71 72 |
# File 'lib/dynamic_scope/processor.rb', line 68 def initialize(scope, params, config) @scope = scope @params = params @config = config end |
Instance Attribute Details
#config ⇒ Object (readonly)
Returns the value of attribute config.
66 67 68 |
# File 'lib/dynamic_scope/processor.rb', line 66 def config @config end |
#params ⇒ Object (readonly)
Returns the value of attribute params.
66 67 68 |
# File 'lib/dynamic_scope/processor.rb', line 66 def params @params end |
Instance Method Details
#scope ⇒ Object
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
# File 'lib/dynamic_scope/processor.rb', line 74 def scope @params.values.inject(@scope) do |memo, query| if (query_scope = DynamicScope::Query.new(@scope, query, @config).scope) if query_scope memo = memo.joins(query_scope.joins_values) if query_scope.try(:joins_values).present? memo = memo.includes(query_scope.includes_values) if query_scope.try(:includes_values).present? memo.distinct.and(query_scope.distinct).distinct else memo.distinct end else memo.distinct end end end |