Class: Philiprehberger::DotAccess::Wrapper
- Inherits:
-
Object
- Object
- Philiprehberger::DotAccess::Wrapper
- Includes:
- Enumerable
- Defined in:
- lib/philiprehberger/dot_access.rb
Overview
Dot-notation wrapper for a hash
Constant Summary collapse
- INDEX_SEGMENT =
Regex matching strings that should be treated as array indices (signed or unsigned integers).
/\A-?\d+\z/
Class Method Summary collapse
-
.parse_pointer(pointer) ⇒ Array<String>
Parse a JSON Pointer string into an array of unescaped segments.
Instance Method Summary collapse
- #==(other) ⇒ Boolean
-
#compact ⇒ Wrapper
Return a new Wrapper with all “nil“ values removed at every depth.
-
#delete(path) ⇒ Wrapper
Remove a key at a dot-path, returning a new Wrapper.
-
#delete_pointer(pointer) ⇒ Wrapper
Delete the value at a JSON Pointer path, returning a new Wrapper.
-
#dig(key) ⇒ Object
private
Dig into nested keys.
-
#each {|Symbol, Object| ... } ⇒ Enumerator
(also: #each_pair)
Iterate over top-level key-value pairs.
-
#empty? ⇒ Boolean
“true“ if the wrapped hash has no keys.
-
#exists?(path) ⇒ Boolean
Check whether a dot-separated path exists in the wrapped structure.
-
#fetch!(path) ⇒ Object
Fetch a value at a dot-path, raising if missing.
-
#flatten ⇒ Hash
Flatten the nested structure into a hash whose keys are dot-paths.
-
#get(path, default: nil) ⇒ Object
Access a value by dot-path string.
-
#get_pointer(pointer, default: nil) ⇒ Object
Access a value by a JSON Pointer (RFC 6901) path.
-
#has_pointer?(pointer) ⇒ Boolean
Whether a JSON Pointer (RFC 6901) path exists in the wrapped structure.
-
#initialize(hash) ⇒ Wrapper
constructor
Wrap the given Hash and freeze the resulting instance.
- #inspect ⇒ String
-
#key?(key) ⇒ Boolean
private
Check if a key exists in the underlying data.
-
#keys(depth: nil) ⇒ Array<String>
List every dot-path in the wrapped structure.
-
#merge(other) ⇒ Wrapper
Deep merge with another Wrapper or Hash.
-
#set(path, value) ⇒ Wrapper
Set a value at a dot-path, returning a new Wrapper.
-
#set_pointer(pointer, value) ⇒ Wrapper
Set a value at a JSON Pointer path, returning a new Wrapper.
-
#size ⇒ Integer
(also: #count)
The number of top-level keys.
-
#slice(*paths) ⇒ Wrapper
Return a new Wrapper containing only the specified dot-paths.
-
#to_h ⇒ Hash
Return the underlying hash with symbol keys.
-
#to_json(*args) ⇒ String
Serialize the wrapped hash to a JSON string.
-
#to_yaml(*args) ⇒ String
Serialize the wrapped hash to a YAML string.
-
#update(paths_hash) ⇒ Wrapper
Batch-set multiple dot-paths, returning a new Wrapper.
-
#values_at(*paths) ⇒ Array<Object>
Return values at the given dot-paths as an array.
Constructor Details
#initialize(hash) ⇒ Wrapper
Wrap the given Hash and freeze the resulting instance.
126 127 128 129 130 131 |
# File 'lib/philiprehberger/dot_access.rb', line 126 def initialize(hash) @data = hash.each_with_object({}) do |(key, value), memo| memo[key.is_a?(String) ? key.to_sym : key] = value end freeze end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(name, *args) ⇒ Object (private)
482 483 484 485 486 487 488 489 490 |
# File 'lib/philiprehberger/dot_access.rb', line 482 def method_missing(name, *args) if @data.key?(name) wrap_value(@data[name]) elsif name.to_s.end_with?('=') || !args.empty? super else NullAccess.new end end |
Class Method Details
.parse_pointer(pointer) ⇒ Array<String>
Parse a JSON Pointer string into an array of unescaped segments. Public so callers and #get_pointer/#set_pointer/etc. share one parser.
346 347 348 349 350 351 352 |
# File 'lib/philiprehberger/dot_access.rb', line 346 def self.parse_pointer(pointer) raise Error, 'pointer must be a String' unless pointer.is_a?(String) return [] if pointer.empty? raise Error, "JSON Pointer must start with '/' (got #{pointer.inspect})" unless pointer.start_with?('/') pointer[1..].split('/', -1).map { |seg| seg.gsub('~1', '/').gsub('~0', '~') } end |
Instance Method Details
#==(other) ⇒ Boolean
474 475 476 477 478 |
# File 'lib/philiprehberger/dot_access.rb', line 474 def ==(other) return to_h == other.to_h if other.is_a?(Wrapper) false end |
#compact ⇒ Wrapper
Return a new Wrapper with all “nil“ values removed at every depth.
364 365 366 |
# File 'lib/philiprehberger/dot_access.rb', line 364 def compact Philiprehberger::DotAccess.wrap(deep_compact(to_h)) end |
#delete(path) ⇒ Wrapper
Remove a key at a dot-path, returning a new Wrapper.
Integer-looking segments delete the matching array element when the current node is an Array.
254 255 256 257 258 |
# File 'lib/philiprehberger/dot_access.rb', line 254 def delete(path) keys = path.to_s.split('.') new_data = deep_delete(to_h, keys) Wrapper.new(new_data) end |
#delete_pointer(pointer) ⇒ Wrapper
Delete the value at a JSON Pointer path, returning a new Wrapper.
333 334 335 336 337 338 |
# File 'lib/philiprehberger/dot_access.rb', line 333 def delete_pointer(pointer) segments = Wrapper.parse_pointer(pointer) raise Error, 'cannot delete the root pointer' if segments.empty? Wrapper.new(deep_delete(to_h, segments)) end |
#dig(key) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Dig into nested keys.
463 464 465 466 |
# File 'lib/philiprehberger/dot_access.rb', line 463 def dig(key) value = @data[key] wrap_value(value) end |
#each {|Symbol, Object| ... } ⇒ Enumerator Also known as: each_pair
Iterate over top-level key-value pairs.
Nested Hash values are yielded as wrapped Philiprehberger::DotAccess::Wrapper instances so block callers can chain dot-notation.
402 403 404 405 406 407 408 |
# File 'lib/philiprehberger/dot_access.rb', line 402 def each(&) return enum_for(:each) unless block_given? @data.each do |key, value| yield key, wrap_value(value) end end |
#empty? ⇒ Boolean
Returns “true“ if the wrapped hash has no keys.
413 414 415 |
# File 'lib/philiprehberger/dot_access.rb', line 413 def empty? @data.empty? end |
#exists?(path) ⇒ Boolean
Check whether a dot-separated path exists in the wrapped structure.
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 |
# File 'lib/philiprehberger/dot_access.rb', line 182 def exists?(path) keys = path.to_s.split('.') current = @data keys.each do |key| case current when Hash return false unless current.key?(key.to_sym) current = current[key.to_sym] when Array index = array_index(key, current) return false if index.nil? current = current[index] when Wrapper return false unless current.key?(key.to_sym) current = current[key.to_sym] else return false end end true end |
#fetch!(path) ⇒ Object
Fetch a value at a dot-path, raising if missing.
220 221 222 223 224 |
# File 'lib/philiprehberger/dot_access.rb', line 220 def fetch!(path) raise KeyError, "path not found: #{path.inspect}" unless exists?(path) get(path) end |
#flatten ⇒ Hash
Flatten the nested structure into a hash whose keys are dot-paths.
357 358 359 |
# File 'lib/philiprehberger/dot_access.rb', line 357 def flatten flatten_hash(@data, '') end |
#get(path, default: nil) ⇒ Object
Access a value by dot-path string.
Path segments that look like integers (e.g. “0“, “-1“) are interpreted as array indices when the value currently being traversed is an Array. Otherwise they are treated as Hash keys.
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 |
# File 'lib/philiprehberger/dot_access.rb', line 142 def get(path, default: nil) keys = path.to_s.split('.') result = keys.reduce(@data) do |current, key| case current when Hash then current[key.to_sym] when Array index = array_index(key, current) return default if index.nil? current[index] when Wrapper then current[key.to_sym] else return default end end result.nil? ? default : result end |
#get_pointer(pointer, default: nil) ⇒ Object
Access a value by a JSON Pointer (RFC 6901) path.
JSON Pointer paths start with ‘/`, separate segments with `/`, and escape `~` as `~0` and `/` as `~1`. An empty pointer (`“”`) refers to the whole wrapped document.
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 |
# File 'lib/philiprehberger/dot_access.rb', line 269 def get_pointer(pointer, default: nil) segments = Wrapper.parse_pointer(pointer) return self if segments.empty? result = segments.reduce(@data) do |current, seg| case current when Hash then current[seg.to_sym] when Array index = array_index(seg, current) return default if index.nil? current[index] else return default end end result.nil? ? default : result end |
#has_pointer?(pointer) ⇒ Boolean
Whether a JSON Pointer (RFC 6901) path exists in the wrapped structure.
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 |
# File 'lib/philiprehberger/dot_access.rb', line 292 def has_pointer?(pointer) segments = Wrapper.parse_pointer(pointer) return true if segments.empty? current = @data segments.each do |seg| case current when Hash return false unless current.key?(seg.to_sym) current = current[seg.to_sym] when Array index = array_index(seg, current) return false if index.nil? current = current[index] else return false end end true end |
#inspect ⇒ String
469 470 471 |
# File 'lib/philiprehberger/dot_access.rb', line 469 def inspect "#<DotAccess::Wrapper #{to_h.inspect}>" end |
#key?(key) ⇒ Boolean
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Check if a key exists in the underlying data.
445 446 447 |
# File 'lib/philiprehberger/dot_access.rb', line 445 def key?(key) @data.key?(key) end |
#keys(depth: nil) ⇒ Array<String>
List every dot-path in the wrapped structure.
211 212 213 |
# File 'lib/philiprehberger/dot_access.rb', line 211 def keys(depth: nil) collect_keys(@data, '', depth, 1) end |
#merge(other) ⇒ Wrapper
Deep merge with another Wrapper or Hash.
372 373 374 375 376 |
# File 'lib/philiprehberger/dot_access.rb', line 372 def merge(other) other_hash = other.is_a?(Wrapper) ? other.to_h : symbolize_keys(other) merged = deep_merge(to_h, other_hash) Wrapper.new(merged) end |
#set(path, value) ⇒ Wrapper
Set a value at a dot-path, returning a new Wrapper.
Integer-looking path segments are applied as array indices when the current node is an Array. Out-of-bounds indices raise ArgumentError; negative indices follow Ruby conventions.
171 172 173 174 175 |
# File 'lib/philiprehberger/dot_access.rb', line 171 def set(path, value) keys = path.to_s.split('.') new_data = deep_set(to_h, keys, value) Wrapper.new(new_data) end |
#set_pointer(pointer, value) ⇒ Wrapper
Set a value at a JSON Pointer path, returning a new Wrapper.
321 322 323 324 325 326 |
# File 'lib/philiprehberger/dot_access.rb', line 321 def set_pointer(pointer, value) segments = Wrapper.parse_pointer(pointer) raise Error, 'cannot set the root pointer' if segments.empty? Wrapper.new(deep_set(to_h, segments, value)) end |
#size ⇒ Integer Also known as: count
Returns the number of top-level keys.
418 419 420 |
# File 'lib/philiprehberger/dot_access.rb', line 418 def size @data.size end |
#slice(*paths) ⇒ Wrapper
Return a new Wrapper containing only the specified dot-paths.
230 231 232 233 234 235 236 237 |
# File 'lib/philiprehberger/dot_access.rb', line 230 def slice(*paths) new_data = paths.reduce({}) do |acc, path| next acc unless exists?(path) deep_set(acc, path.to_s.split('.'), get(path)) end Wrapper.new(new_data) end |
#to_h ⇒ Hash
Return the underlying hash with symbol keys.
452 453 454 455 456 |
# File 'lib/philiprehberger/dot_access.rb', line 452 def to_h @data.each_with_object({}) do |(key, value), memo| memo[key] = value.is_a?(Wrapper) ? value.to_h : value end end |
#to_json(*args) ⇒ String
Serialize the wrapped hash to a JSON string.
428 429 430 |
# File 'lib/philiprehberger/dot_access.rb', line 428 def to_json(*args) to_h.to_json(*args) end |
#to_yaml(*args) ⇒ String
Serialize the wrapped hash to a YAML string.
436 437 438 |
# File 'lib/philiprehberger/dot_access.rb', line 436 def to_yaml(*args) to_h.to_yaml(*args) end |
#update(paths_hash) ⇒ Wrapper
Batch-set multiple dot-paths, returning a new Wrapper.
Applies every entry in “paths_hash“ in iteration order, following the same semantics as #set. The receiver is not mutated.
388 389 390 391 392 393 |
# File 'lib/philiprehberger/dot_access.rb', line 388 def update(paths_hash) new_data = paths_hash.reduce(to_h) do |acc, (path, value)| deep_set(acc, path.to_s.split('.'), value) end Wrapper.new(new_data) end |
#values_at(*paths) ⇒ Array<Object>
Return values at the given dot-paths as an array.
243 244 245 |
# File 'lib/philiprehberger/dot_access.rb', line 243 def values_at(*paths) paths.map { |path| get(path) } end |