Add option to treat strings starting with $ as JSONPath

This commit is contained in:
Andrew Cantino 2014-04-05 17:04:06 -07:00
parent 0e7c5c5b95
commit 63a42fff3c
2 changed files with 20 additions and 9 deletions

View file

@ -21,20 +21,24 @@ module Utils
end
end
def self.interpolate_jsonpaths(value, data)
value.gsub(/<[^>]+>/).each { |jsonpath|
Utils.values_at(data, jsonpath[1..-2]).first.to_s
}
def self.interpolate_jsonpaths(value, data, options = {})
if options[:leading_dollarsign_is_jsonpath] && value[0] == '$'
Utils.values_at(data, value).first.to_s
else
value.gsub(/<[^>]+>/).each { |jsonpath|
Utils.values_at(data, jsonpath[1..-2]).first.to_s
}
end
end
def self.recursively_interpolate_jsonpaths(struct, data)
def self.recursively_interpolate_jsonpaths(struct, data, options = {})
case struct
when Hash
struct.inject({}) {|memo, (key, value)| memo[key] = recursively_interpolate_jsonpaths(value, data); memo }
struct.inject({}) {|memo, (key, value)| memo[key] = recursively_interpolate_jsonpaths(value, data, options); memo }
when Array
struct.map {|elem| recursively_interpolate_jsonpaths(elem, data) }
struct.map {|elem| recursively_interpolate_jsonpaths(elem, data, options) }
when String
interpolate_jsonpaths(struct, data)
interpolate_jsonpaths(struct, data, options)
else
struct
end

View file

@ -28,8 +28,15 @@ describe Utils do
end
describe "#interpolate_jsonpaths" do
let(:payload) { { :there => { :world => "WORLD" }, :works => "should work" } }
it "interpolates jsonpath expressions between matching <>'s" do
Utils.interpolate_jsonpaths("hello <$.there.world> this <escape works>", { :there => { :world => "WORLD" }, :works => "should work" }).should == "hello WORLD this should+work"
Utils.interpolate_jsonpaths("hello <$.there.world> this <escape works>", payload).should == "hello WORLD this should+work"
end
it "optionally supports treating values that start with '$' as raw JSONPath" do
Utils.interpolate_jsonpaths("$.there.world", payload).should == "$.there.world"
Utils.interpolate_jsonpaths("$.there.world", payload, :leading_dollarsign_is_jsonpath => true).should == "WORLD"
end
end