Class: Core::Io::Json::Grammar::Leaf

Inherits:
Object
  • Object
show all
Defined in:
app/api/core/io/json/grammar.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, attribute) ⇒ Leaf

Returns a new instance of Leaf.



146
147
148
149
150
# File 'app/api/core/io/json/grammar.rb', line 146

def initialize(name, attribute)
  @name = name
  @attribute = attribute.pop
  @attribute_path = attribute
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



144
145
146
# File 'app/api/core/io/json/grammar.rb', line 144

def name
  @name
end

Instance Method Details

#call(object, options, stream) ⇒ Object



152
153
154
155
156
157
158
159
160
# File 'app/api/core/io/json/grammar.rb', line 152

def call(object, options, stream)
  value =
    @attribute_path.inject(object) do |o, k|
      return if o.nil?
      o.send(k)
    end or return

  stream.attribute(@name, value.send(@attribute), options)
end

#dupObject



162
163
164
165
# File 'app/api/core/io/json/grammar.rb', line 162

def dup
  attribute = @attribute_path.dup.tap { |p| p << @attribute }
  self.class.new(name, attribute)
end

#inspectObject



178
179
180
# File 'app/api/core/io/json/grammar.rb', line 178

def inspect
  "Leaf<#{@name},#{@attribute},#{@attribute_path.inspect}>"
end

#merge(_node) ⇒ Object



167
168
169
# File 'app/api/core/io/json/grammar.rb', line 167

def merge(_node)
  raise 'Cannot merge into a leaf as it is attribute only!'
end

#merge_children_with(node) ⇒ Object



171
172
173
174
175
176
# File 'app/api/core/io/json/grammar.rb', line 171

def merge_children_with(node)
  key = "_#{name}"
  raise "Cannot merge as existing leaf node '#{key}'" if node.children.key?(key)

  node.children.merge(key => self)
end