Class: Jason::ConditionsMatcher

Inherits:
Object
  • Object
show all
Defined in:
lib/jason/conditions_matcher.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(klass) ⇒ ConditionsMatcher

Returns a new instance of ConditionsMatcher.



4
5
6
# File 'lib/jason/conditions_matcher.rb', line 4

def initialize(klass)
  @klass = klass
end

Instance Attribute Details

#klassObject (readonly)

Returns the value of attribute klass.



2
3
4
# File 'lib/jason/conditions_matcher.rb', line 2

def klass
  @klass
end

Instance Method Details

#apply_conditions(relation, conditions) ⇒ Object

conditions = { ‘post_id’ => 123, ‘created_at’ => { ‘type’ => ‘between’, ‘value’ => [‘2020-01-01’, ‘2020-01-02’] } }



43
44
45
46
47
48
49
# File 'lib/jason/conditions_matcher.rb', line 43

def apply_conditions(relation, conditions)
  conditions.each do |key, rules|
    relation = apply_condition(relation, key, rules)
  end

  relation
end

#test_match(key, rules, previous_changes) ⇒ Object

key, rules = ‘post_id’, 123 key, rules = ‘post_id’, { ‘value’: [123,C456], ‘type’: ‘between’ } key, rules = ‘post_id’, { ‘value’: [123,456], ‘type’: ‘between’, ‘not’: true } key, rules = ‘post_id’, { ‘value’: 123, ‘type’: ‘equals’, ‘not’: true }



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
38
39
40
# File 'lib/jason/conditions_matcher.rb', line 12

def test_match(key, rules, previous_changes)
  return nil if !previous_changes.keys.include?(key)

  if rules.is_a?(Hash)
    matches = false
    value = convert_to_datatype(key, rules['value'])

    if rules['type'] == 'equals'
      matches = previous_changes[key][1] == value
    elsif rules['type'] == 'between'
      matches = (value[0]..value[1]).cover?(previous_changes[key][1])
    else
      raise "Unrecognized rule type #{rules['type']}"
    end

    if rules['not']
      return !matches
    else
      return matches
    end

  elsif rules.is_a?(Array)
    value = convert_to_datatype(key, rules)
    return previous_changes[key][1].includes?(value)
  else
    value = convert_to_datatype(key, rules)
    return previous_changes[key][1] == value
  end
end