Class: MiniDefender::RulesExpander

Inherits:
Object
  • Object
show all
Defined in:
lib/mini_defender/rules_expander.rb

Instance Method Summary collapse

Instance Method Details

#array_patterns(rules) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/mini_defender/rules_expander.rb', line 35

def array_patterns(rules)
  unless rules.is_a?(Hash)
    raise ArgumentError, 'Rules must be a Hash'
  end

  result = rules.keys.filter { |key| key.include?('*') }

  # If the user hasn't add a rule for each of the array elements, add it manually
  rules.keys.each do |key|
    current = []
    key.split('.').each do |section|
      current << section
      result << current.join('.') if section == '*'
    end
  end

  result.sort.uniq.map { |key| Regexp.compile('\A' + key.gsub(/\*/, '\d+') + '\Z') }
end

#expand(rules, flat_data) ⇒ Hash

Parameters:

  • rules (Hash)
  • flat_data (Hash)

Returns:

  • (Hash)


8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/mini_defender/rules_expander.rb', line 8

def expand(rules, flat_data)
  result = {}

  rules.each do |rule_key, rule_set|
    unless rule_key.include?('*')
      result[rule_key] = rule_set
      next
    end

    k_pattern = Regexp.compile('\A' + rule_key.gsub(/\*/, '\d+') + '\Z')
    k_pattern_result = {}

    flat_data.each do |value_key, _|
      next unless k_pattern.match?(value_key)
      k_pattern_result[value_key] = rule_set
    end

    if k_pattern_result.empty?
      k_pattern_result[k_pattern.source.gsub(/\\[AZ]/, '').gsub('\d+', '0')] = rule_set
    end

    result.merge!(k_pattern_result)
  end

  result
end