Module: Philiprehberger::DotAccess
- Defined in:
- lib/philiprehberger/dot_access.rb,
lib/philiprehberger/dot_access/version.rb
Defined Under Namespace
Classes: Error, NullAccess, Wrapper
Constant Summary collapse
- VERSION =
'0.7.0'
Class Method Summary collapse
-
.from_flat(hash) ⇒ Wrapper
Build a Wrapper from a hash whose keys are dot-paths.
-
.from_json(str) ⇒ Wrapper
Parse a JSON string and wrap the result.
-
.from_yaml(str_or_path) ⇒ Wrapper
Parse a YAML string or file path and wrap the result.
-
.wrap(hash) ⇒ Wrapper
Wrap a hash for dot-notation access.
Class Method Details
.from_flat(hash) ⇒ Wrapper
Build a Wrapper from a hash whose keys are dot-paths.
Inverse of Philiprehberger::DotAccess::Wrapper#flatten — passing the result of ‘wrap(h).flatten` back through `from_flat` reconstructs the original (symbol-keyed) structure. Arrays are preserved as opaque values: `#flatten` does not explode array elements into separate dot-paths, and `from_flat` therefore cannot create new array slots from integer-only segments.
48 49 50 51 52 53 54 |
# File 'lib/philiprehberger/dot_access.rb', line 48 def self.from_flat(hash) raise Error, 'Expected a Hash' unless hash.is_a?(Hash) hash.reduce(wrap({})) do |wrapper, (path, value)| wrapper.set(path, value) end end |
.from_json(str) ⇒ Wrapper
Parse a JSON string and wrap the result
61 62 63 64 |
# File 'lib/philiprehberger/dot_access.rb', line 61 def self.from_json(str) data = JSON.parse(str) wrap(normalize_keys(data)) end |
.from_yaml(str_or_path) ⇒ Wrapper
Parse a YAML string or file path and wrap the result
27 28 29 30 31 32 33 34 35 |
# File 'lib/philiprehberger/dot_access.rb', line 27 def self.from_yaml(str_or_path) data = if File.exist?(str_or_path) YAML.safe_load_file(str_or_path, permitted_classes: [Symbol]) else YAML.safe_load(str_or_path, permitted_classes: [Symbol]) end wrap(normalize_keys(data)) end |