Class: Cuprum::Collections::Scopes::Criteria::Parser
- Inherits:
-
Object
- Object
- Cuprum::Collections::Scopes::Criteria::Parser
- Defined in:
- lib/cuprum/collections/scopes/criteria/parser.rb
Overview
Helper for generating criteria from hash or block inputs.
Defined Under Namespace
Classes: BlockParser
Class Method Summary collapse
-
.instance ⇒ Cuprum::Collections::Scopes::Criteria::Parser
A singleton instance of the parser class.
- .validate_hash(value) ⇒ Object
Instance Method Summary collapse
-
#parse(value = nil) { ... } ⇒ Array
Converts a valid query hash and/or block to criteria.
-
#parse_block { ... } ⇒ Array
Converts a valid query block to criteria.
-
#parse_hash(value) ⇒ Array
Converts a hash of expected keys and values to criteria.
Class Method Details
.instance ⇒ Cuprum::Collections::Scopes::Criteria::Parser
Returns a singleton instance of the parser class.
112 113 114 |
# File 'lib/cuprum/collections/scopes/criteria/parser.rb', line 112 def instance @instance ||= new end |
.validate_hash(value) ⇒ Object
117 118 119 120 121 122 123 |
# File 'lib/cuprum/collections/scopes/criteria/parser.rb', line 117 def validate_hash(value) return if valid_hash?(value) = 'value must be a Hash with String or Symbol keys' raise ArgumentError, , caller(1..-1) end |
Instance Method Details
#parse(value = nil) { ... } ⇒ Array
150 151 152 153 154 155 156 157 158 159 160 |
# File 'lib/cuprum/collections/scopes/criteria/parser.rb', line 150 def parse(value = UNKNOWN, &) if block_given? && value != UNKNOWN parse_hash(value) + parse_block(&) elsif value.is_a?(Proc) parse_block(&value) elsif value == UNKNOWN parse_block(&) else parse_hash(value) end end |
#parse_block { ... } ⇒ Array
Converts a valid query block to criteria.
The block must return a Hash with String keys. The hash values must either be literal values (e.g. a String, an Integer, etc) or a call to an operator function.
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 |
# File 'lib/cuprum/collections/scopes/criteria/parser.rb', line 173 def parse_block(...) # rubocop:disable Metrics/MethodLength raise ArgumentError, 'no block given' unless block_given? value = evaluate_block(...) Parser.validate_hash(value) value.map do |attribute, filter| if filter.is_a?(OperatorExpression) [attribute.to_s, filter.operator, filter.value] else operator = Cuprum::Collections::Queries::Operators::EQUAL [attribute.to_s, operator, filter] end end rescue NameError => exception raise Cuprum::Collections::Queries::UnknownOperatorException, %(unknown operator "#{exception.name}") end |
#parse_hash(value) ⇒ Array
Converts a hash of expected keys and values to criteria.
199 200 201 202 203 204 205 206 207 |
# File 'lib/cuprum/collections/scopes/criteria/parser.rb', line 199 def parse_hash(value) Parser.validate_hash(value) operator = Cuprum::Collections::Queries::Operators::EQUAL value.map do |attribute, filter| [attribute.to_s, operator, filter] end end |