Module: LogStash::Util::FieldReference

Extended by:
FieldReference
Included in:
FieldReference
Defined in:
lib/logstash/util/fieldreference.rb

Instance Method Summary collapse

Instance Method Details

#compile(accessor) ⇒ Object



7
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
34
35
36
37
# File 'lib/logstash/util/fieldreference.rb', line 7

def compile(accessor)
  if accessor[0,1] != '['
    return "      lambda do |store, &block|\n        return block.nil? ? store[\#{accessor.inspect}] : block.call(store, \#{accessor.inspect})\n      end\n    CODE\n  end\n\n  code = \"lambda do |store, &block|\\n\"\n  selectors = accessor.scan(/(?<=\\[).+?(?=\\])/)\n  selectors.each_with_index do |tok, i|\n    last = (i == selectors.count() - 1)\n    code << \"   # [\#{tok}]\#{ last ? \" (last selector)\" : \"\" }\\n\"\n\n    if last\n      code << <<-\"CODE\"\n        return block.call(store, \#{tok.inspect}) unless block.nil?\n      CODE\n    end\n\n    code << <<-\"CODE\"\n      store = store.is_a?(Array) ? store[\#{tok.to_i}] : store[\#{tok.inspect}]\n      return store if store.nil?\n    CODE\n\n  end\n  code << \"return store\\nend\"\n  #puts code\n  return code\nend\n"

#exec(accessor, store, &block) ⇒ Object

def compile



39
40
41
42
43
# File 'lib/logstash/util/fieldreference.rb', line 39

def exec(accessor, store, &block)
  @__fieldeval_cache ||= {}
  @__fieldeval_cache[accessor] ||= eval(compile(accessor))
  return @__fieldeval_cache[accessor].call(store, &block)
end

#set(accessor, value, store) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/logstash/util/fieldreference.rb', line 45

def set(accessor, value, store)
  # The assignment can fail if the given field reference (accessor) does not exist
  # In this case, we'll want to set the value manually.
  if exec(accessor, store) { |hash, key| hash[key] = value }.nil?
    return (store[accessor] = value) if accessor[0,1] != "["

    # No existing element was found, so let's set one.
    *parents, key = accessor.scan(/(?<=\[)[^\]]+(?=\])/)
    parents.each do |p|
      if store.include?(p)
        store = store[p]
      else
        store[p] = {}
        store = store[p]
      end
    end
    store[key] = value
  end

  return value
end