Class: Cel::Context

Inherits:
Object
  • Object
show all
Defined in:
lib/cel/context.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(environment, bindings) ⇒ Context

Returns a new instance of Context.



7
8
9
10
# File 'lib/cel/context.rb', line 7

def initialize(environment, bindings)
  @environment = environment
  @bindings = bindings.dup
end

Instance Attribute Details

#bindingsObject (readonly)

Returns the value of attribute bindings.



5
6
7
# File 'lib/cel/context.rb', line 5

def bindings
  @bindings
end

Instance Method Details

#declarationsObject



12
13
14
# File 'lib/cel/context.rb', line 12

def declarations
  @environment.declarations
end

#lookup(identifier) ⇒ Object

Raises:



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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/cel/context.rb', line 16

def lookup(identifier)
  raise EvaluateError, "no value in context for #{identifier}" unless @bindings

  id = identifier.to_s

  lookup_keys = id.split(".")

  val = @bindings

  loop do
    fetched = false
    (0...lookup_keys.size).reverse_each do |idx|
      key = lookup_keys[0..idx].join(".").to_sym
      is_binding = val == @bindings

      val = if val.respond_to?(:key?)
        # hash
        next unless val.key?(key)

        val[key]
      else
        next unless val.respond_to?(key)

        case val
        when Protobuf.base_class
          Protobuf.lookup(val, key)
        else
          val.__send__(key)
        end
      end

      val = @bindings[key] = to_cel_primitive(key, val) if is_binding
      lookup_keys = lookup_keys[(idx + 1)..]
      fetched = true
      break
    end

    break unless fetched

    break if lookup_keys.empty?
  end

  raise EvaluateError, "no value in context for #{id}" if val == @bindings

  # lookup_keys.each do |key|
  #   raise EvaluateError, "no value in context for #{id}" unless val.key?(key)

  #   val = val[key]
  # end

  [val, lookup_keys.empty? ? nil : lookup_keys.join(".")]
end

#merge(bindings) ⇒ Object



69
70
71
# File 'lib/cel/context.rb', line 69

def merge(bindings)
  Context.new(@environment, @bindings ? @bindings.merge(bindings) : bindings)
end