Module: Dotpath

Defined in:
lib/dotpath.rb,
lib/dotpath/walk.rb,
lib/dotpath/mutate.rb,
lib/dotpath/version.rb,
lib/dotpath/extension.rb

Defined Under Namespace

Modules: Extension Classes: Mutate, Walk

Constant Summary collapse

DELIMITER =
'.'
VERSION =
'0.1.0'

Class Method Summary collapse

Class Method Details

.encode(key) ⇒ Object



12
13
14
15
# File 'lib/dotpath.rb', line 12

def self.encode(key)
  key = key.to_s
  key.include?(DELIMITER) ? "\"#{key}\"" : key
end

.value_at_path(object, json_path) ⇒ Object

Retrieve a value at a given JSON path for an Array or Hash.

Parameters:

  • object (Hash, Array)

    The object that can be navigated using JSON path.

  • json_path (String)

    The JSON path for the requested value.

Returns:

  • the value at JSON path.

Raises:

  • (ArgumentError)


23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/dotpath.rb', line 23

def self.value_at_path(object, json_path)
  raise ArgumentError, "#{object.class} does not support JSON path" unless object.respond_to?(:each_with_json_path)

  val = nil
  object.each_with_json_path do |path, value|
    if json_path == path
      val = value
      break
    end
  end
  val
end