Class: TomlRB::Keyvalue

Inherits:
Object
  • Object
show all
Defined in:
lib/toml-rb/keyvalue.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(dotted_keys, value) ⇒ Keyvalue

Returns a new instance of Keyvalue.



7
8
9
10
11
# File 'lib/toml-rb/keyvalue.rb', line 7

def initialize(dotted_keys, value)
  @dotted_keys = dotted_keys
  @value = value
  @symbolize_keys = false
end

Instance Attribute Details

#dotted_keysObject (readonly)

Returns the value of attribute dotted_keys.



5
6
7
# File 'lib/toml-rb/keyvalue.rb', line 5

def dotted_keys
  @dotted_keys
end

#symbolize_keysObject (readonly)

Returns the value of attribute symbolize_keys.



5
6
7
# File 'lib/toml-rb/keyvalue.rb', line 5

def symbolize_keys
  @symbolize_keys
end

#valueObject (readonly)

Returns the value of attribute value.



5
6
7
# File 'lib/toml-rb/keyvalue.rb', line 5

def value
  @value
end

Instance Method Details

#accept_visitor(parser) ⇒ Object



45
46
47
# File 'lib/toml-rb/keyvalue.rb', line 45

def accept_visitor(parser)
  parser.visit_keyvalue self
end

#assign(hash, fully_defined_keys, symbolize_keys = false) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/toml-rb/keyvalue.rb', line 13

def assign(hash, fully_defined_keys, symbolize_keys = false)
  @symbolize_keys = symbolize_keys
  dotted_keys_str = @dotted_keys.join(".")
  keys = symbolize_keys ? @dotted_keys.map(&:to_sym) : @dotted_keys
  update = keys.reverse.inject(visit_value(@value)) { |k1, k2| {k2 => k1} }

  parent_inline_table = fully_defined_keys.find { |k| dotted_keys_str.start_with?("#{k}.") }
  fail ValueOverwriteError.new(@dotted_keys.first) if parent_inline_table

  if @value.is_a?(InlineTable)
    child_keys_exist = fully_defined_keys.find { |k| k.start_with?("#{dotted_keys_str}.") }
    fail ValueOverwriteError.new(@dotted_keys.first) if child_keys_exist

    existing_hash = hash.dig(*keys)
    fail ValueOverwriteError.new(@dotted_keys.first) if existing_hash.is_a?(Hash) && !existing_hash.empty?

    fully_defined_keys << dotted_keys_str
  end

  dotted_key_merge(hash, update)
end

#dotted_key_merge(hash, update) ⇒ Object



35
36
37
38
39
40
41
42
43
# File 'lib/toml-rb/keyvalue.rb', line 35

def dotted_key_merge(hash, update)
  hash.merge!(update) do |key, old, new|
    if old.is_a?(Hash) && new.is_a?(Hash)
      dotted_key_merge(old, new)
    else
      fail ValueOverwriteError.new(key)
    end
  end
end