diff options
-rw-r--r-- | lib/puppet/parser/functions/couchdblookup.rb | 24 | ||||
-rw-r--r-- | spec/unit/data/map+reduce.txt | 3 | ||||
-rwxr-xr-x | spec/unit/puppet/parser/functions/couchdblookup_spec.rb | 16 |
3 files changed, 35 insertions, 8 deletions
diff --git a/lib/puppet/parser/functions/couchdblookup.rb b/lib/puppet/parser/functions/couchdblookup.rb index 2e1545e..8c4bc21 100644 --- a/lib/puppet/parser/functions/couchdblookup.rb +++ b/lib/puppet/parser/functions/couchdblookup.rb @@ -20,15 +20,23 @@ module Puppet::Parser::Functions end result = nil - if json.has_key?("rows") and json['total_rows'] > 0 and json['rows'][0].has_key?(key) - result = Array.new - json['rows'].each do |x| - result.push(x[key]) - end - else - if json.has_key?(key) - result = json[key] + + if json.has_key?("rows") + + if json['rows'].length > 1 + arr = json['rows'].collect do |x| + x[key] if x.is_a?(Hash) and x.has_key?(key) + end + arr.compact! + result = arr unless arr.empty? + + elsif json['rows'].length == 1 + hash = json['rows'].pop + result = hash[key] if hash.is_a?(Hash) end + + elsif json.has_key?(key) + result = json[key] end result or raise Puppet::ParseError, "couchdblookup(): key '#{key}' not found in JSON object !" diff --git a/spec/unit/data/map+reduce.txt b/spec/unit/data/map+reduce.txt new file mode 100644 index 0000000..71e1836 --- /dev/null +++ b/spec/unit/data/map+reduce.txt @@ -0,0 +1,3 @@ +{"rows":[ +{"key":1,"value":["foo","bar","baz"]} +]} diff --git a/spec/unit/puppet/parser/functions/couchdblookup_spec.rb b/spec/unit/puppet/parser/functions/couchdblookup_spec.rb index 4e9ab76..2af51a9 100755 --- a/spec/unit/puppet/parser/functions/couchdblookup_spec.rb +++ b/spec/unit/puppet/parser/functions/couchdblookup_spec.rb @@ -54,4 +54,20 @@ describe "the couchdblookup function" do result.should raise_error(Puppet::ParseError) end + it "should return an array the values from a couchdb reduced view" do + sample_json = File.open(@datapath + 'map+reduce.txt') + OpenURI.stub!(:open_uri).and_return(sample_json) + + result = @scope.function_couchdblookup(["http://fake/uri", "value"]) + result.should eq(["foo", "bar", "baz"]) + end + + it "should raise a ParseError if a key can't be found in the rows of a couchdb reduced view" do + sample_json = File.open(@datapath + 'map+reduce.txt') + OpenURI.stub!(:open_uri).and_return(sample_json) + + result = lambda { @scope.function_couchdblookup(["http://fake/uri", "fake-key"]) } + result.should raise_error(Puppet::ParseError) + end + end |