Class: HashToConditions::ArrayHelper
- Inherits:
-
Object
- Object
- HashToConditions::ArrayHelper
- Defined in:
- lib/helpers/array_helper.rb
Overview
This helper class takes a Hash key-value pair (an Array) and return the expanded form condition.
For example:
> helper = ArrayHelper.new(['age.gt', 18])
> helper.to_condition => ['age>?', 18]
Instance Method Summary collapse
-
#to_condition ⇒ Object
Returns an expanded form condition or a Hash if it is a nested condition.
Instance Method Details
#to_condition ⇒ Object
Returns an expanded form condition or a Hash if it is a nested condition.
An exception is raised when specific validation fails. Possible exception messages are:
-
‘bad_key_value_pair’ - array must have exactly two (2) elements
-
‘field_cannot_be_empty’ - a field name must be specified
-
‘unknown_operator’ - operator tag is not supported
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/helpers/array_helper.rb', line 18 def to_condition raise "bad_key_value_pair" unless @array.length == 2 parts = @array.first.to_s.split('.') raise "field_cannot_be_empty" if parts.empty? field = parts[0].strip.to_s operator = parts[1] value = @array.last if ['AND', 'OR'].index(field.upcase) # handle nested condition return {field.upcase => value} end unless operator # handle implicit .eq ({'name' => 'value'}) or .like ({'name' => 'value%'}) operator = value.to_s.index('%') ? 'like' : 'eq' end operator = operator.to_s.downcase mapped = operator.to_operator raise "unknown_operator" unless mapped # handle .null or .nnull, suppress value return [field + mapped] if operator.index('null') return [field + mapped, value] unless ['in', 'between'].index(operator) handle_in_between(operator, field, mapped, value) end |