Class: Cel::Map

Inherits:
Literal
  • Object
show all
Defined in:
lib/cel/ast/elements/map.rb

Constant Summary collapse

ALLOWED_TYPES =
%i[int uint bool string].map { |typ| TYPES[typ] }.freeze

Instance Attribute Summary collapse

Attributes inherited from Literal

#type, #value

Instance Method Summary collapse

Methods inherited from Literal

to_cel_type

Methods included from CelMethods

included

Constructor Details

#initialize(value, depth: 1) ⇒ Map

Returns a new instance of Map.



9
10
11
12
13
14
15
16
# File 'lib/cel/ast/elements/map.rb', line 9

def initialize(value, depth: 1)
  # store array internally to support repeated keys
  value = value.map do |k, v|
    [Literal.to_cel_type(k), Literal.to_cel_type(v)]
  end
  super(TYPES[:map], value)
  @depth = depth
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(meth, *args) ⇒ Object



97
98
99
100
101
102
103
104
105
106
# File 'lib/cel/ast/elements/map.rb', line 97

def method_missing(meth, *args)
  return super unless @value

  meth_s = meth.to_s
  values = @value.filter_map { |k, v| v if k == meth_s }

  return super if values.empty?

  values.first
end

Instance Attribute Details

#depthObject (readonly)

Returns the value of attribute depth.



7
8
9
# File 'lib/cel/ast/elements/map.rb', line 7

def depth
  @depth
end

Instance Method Details

#==(other) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/cel/ast/elements/map.rb', line 18

def ==(other)
  case other
  when Map
    @value.all? do |args|
      other.value.include?(args)
    end
  when Array
    # calls to != will downgrade maps to arrays
    @value.all? do |args|
      other.include?(args)
    end
  else
    super
  end
end

#key?(key) ⇒ Boolean Also known as: include?

Returns:

  • (Boolean)


44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/cel/ast/elements/map.rb', line 44

def key?(key)
  ukey =
    case key
    when Symbol
      key.to_s
    when String
      key.delete_prefix('"').delete_suffix('"')
    else
      key
    end

  @value.any? do |k, _v|
    k == ukey
  end
end

#respond_to_missing?(meth, *args) ⇒ Boolean

Returns:

  • (Boolean)


88
89
90
91
92
93
94
95
# File 'lib/cel/ast/elements/map.rb', line 88

def respond_to_missing?(meth, *args)
  return true if super
  return false unless @value

  meth_s = meth.to_s

  @value.any? { |k, _| k == meth_s }
end

#to_ruby_typeObject



84
85
86
# File 'lib/cel/ast/elements/map.rb', line 84

def to_ruby_type
  value.to_h { |args| args.map(&:to_ruby_type) }
end