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.5.0'

Class Method Summary collapse

Class Method Details

.from_json(str) ⇒ Wrapper

Parse a JSON string and wrap the result

Parameters:

  • str (String)

    JSON string

Returns:

  • (Wrapper)

    a dot-accessible wrapper

Raises:

  • (Error)

    if the parsed result is not a Hash



42
43
44
45
# File 'lib/philiprehberger/dot_access.rb', line 42

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

Parameters:

  • str_or_path (String)

    YAML string or path to a YAML file

Returns:

  • (Wrapper)

    a dot-accessible wrapper

Raises:

  • (Error)

    if the parsed result is not a Hash



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

.wrap(hash) ⇒ Wrapper

Wrap a hash for dot-notation access

Parameters:

  • hash (Hash)

    the hash to wrap

Returns:

  • (Wrapper)

    a dot-accessible wrapper

Raises:

  • (Error)

    if argument is not a Hash



16
17
18
19
20
# File 'lib/philiprehberger/dot_access.rb', line 16

def self.wrap(hash)
  raise Error, 'Expected a Hash' unless hash.is_a?(Hash)

  Wrapper.new(hash)
end