Class: Shokkenki::Term::JsonPathExample

Inherits:
Object
  • Object
show all
Defined in:
lib/shokkenki/term/json_path_example.rb

Constant Summary collapse

ELEMENT_HANDLERS =
{
  /^\['(.+)'\]$/ => lambda{ |match, ancestor, value| ancestor[match[1]] = value },
  /\*/ => lambda{ |m, a, v| a['wildcard'] = v },
  /\.\./ => lambda{ |m, a, v| a },
  /\$/ => lambda{ |m, a, v| a }, # ignore root element
  /^\[\d+\]$/ => lambda{ |m, a, v| raise "Numeric element '#{m[0]}' is not supported."},
  /^\[\?.*\]$/ => lambda{ |m, a, v| raise "Filter element '#{m[0]}' is not supported."},
  /^\[.*,.*\]$/ => lambda{ |m, a, v| raise "Union element '#{m[0]}' is not supported."},
  /^\[.*:.*\]$/ => lambda{ |m, a, v| raise "Array slice element '#{m[0]}' is not supported."},
  /^\[.*\(.*\]$/ => lambda{ |m, a, v| raise "Script element '#{m[0]}' is not supported."},
  /.*/ => lambda{ |m, a, v| raise "Unrecognised element '#{m[0]}' is not supported."}
}

Instance Method Summary collapse

Constructor Details

#initialize(path, term) ⇒ JsonPathExample

Returns a new instance of JsonPathExample.



20
21
22
23
# File 'lib/shokkenki/term/json_path_example.rb', line 20

def initialize path, term
  @path = path
  @term = term
end

Instance Method Details

#to_exampleObject



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/shokkenki/term/json_path_example.rb', line 25

def to_example
  example = {}
  path = JsonPath.new(@path).path
  last = path.pop

  begin
    leaf = path.inject(example) do |ancestor, element|
      store ancestor, element
    end

    store leaf, last, @term.example
  rescue Exception => e
    raise "Could not generate example for JSON path '#{@path}': #{e.message}"
  end

  example
end