Module: Philiprehberger::TomlKit::Query
- Defined in:
- lib/philiprehberger/toml_kit/query.rb
Overview
Dot-path query access for nested TOML hashes.
Supports:
- Simple dot paths: "database.host"
- Array indexing: "servers[0].name"
- Deep nesting: "a.b.c.d"
Class Method Summary collapse
-
.delete(data, path) ⇒ Object?
Delete a value at the given path.
-
.exists?(data, path) ⇒ Boolean
Check whether a path exists in the data.
-
.get(data, path, default: nil) ⇒ Object
Retrieve a value from a nested hash using a dot-path.
-
.set(data, path, value) ⇒ Object
Set a value in a nested hash using a dot-path.
Class Method Details
.delete(data, path) ⇒ Object?
Delete a value at the given path.
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
# File 'lib/philiprehberger/toml_kit/query.rb', line 81 def self.delete(data, path) segments = parse_path(path) return nil if segments.empty? parent = segments.length > 1 ? get(data, build_path(segments[0...-1])) : data return nil unless parent last = segments.last case last when Integer parent.is_a?(Array) ? parent.delete_at(last) : nil when String parent.is_a?(Hash) ? parent.delete(last) : nil end end |
.exists?(data, path) ⇒ Boolean
Check whether a path exists in the data.
71 72 73 74 |
# File 'lib/philiprehberger/toml_kit/query.rb', line 71 def self.exists?(data, path) sentinel = Object.new get(data, path, default: sentinel) != sentinel end |
.get(data, path, default: nil) ⇒ Object
Retrieve a value from a nested hash using a dot-path.
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/philiprehberger/toml_kit/query.rb', line 18 def self.get(data, path, default: nil) segments = parse_path(path) current = data segments.each do |segment| case segment when Integer return default unless current.is_a?(Array) && segment < current.length current = current[segment] when String return default unless current.is_a?(Hash) && current.key?(segment) current = current[segment] end end current end |
.set(data, path, value) ⇒ Object
Set a value in a nested hash using a dot-path. Creates intermediate hashes/arrays as needed.
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
# File 'lib/philiprehberger/toml_kit/query.rb', line 45 def self.set(data, path, value) segments = parse_path(path) current = data segments[0...-1].each_with_index do |segment, idx| next_segment = segments[idx + 1] case segment when Integer current[segment] = next_segment.is_a?(Integer) ? [] : {} unless current[segment] current = current[segment] when String current[segment] = next_segment.is_a?(Integer) ? [] : {} unless current.key?(segment) current = current[segment] end end current[segments.last] = value value end |