From 80c50ccf8f46bfd623357bcc7a56f67aec282037 Mon Sep 17 00:00:00 2001 From: Chris Anderson Date: Sat, 17 May 2008 13:41:16 -0700 Subject: [PATCH] got reduce support working for javascript views --- lib/database.rb | 12 ++++++++++-- spec/database_spec.rb | 17 +++++++++++++++-- 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/lib/database.rb b/lib/database.rb index 4c4f80f..6d72265 100644 --- a/lib/database.rb +++ b/lib/database.rb @@ -13,8 +13,16 @@ class CouchRest CouchRest.get "#{@root}/_all_docs" end - def temp_view func - JSON.parse(RestClient.post("#{@root}/_temp_view", func, {"Content-Type" => "text/javascript"})) + def temp_view map, reduce = nil + if reduce + funcs = { + :map => map, + :reduce => reduce + } + else + funcs = map + end + JSON.parse(RestClient.post("#{@root}/_temp_view", JSON.unparse(funcs), {"Content-Type" => "text/javascript"})) end def view name diff --git a/spec/database_spec.rb b/spec/database_spec.rb index 037f6f0..4f73dd2 100644 --- a/spec/database_spec.rb +++ b/spec/database_spec.rb @@ -16,7 +16,7 @@ describe CouchRest::Database do end end - describe "query with _temp_view in Javascript" do + describe "map query with _temp_view in Javascript" do before(:each) do @db.bulk_save([ {"wild" => "and random"}, @@ -30,6 +30,20 @@ describe CouchRest::Database do end end + describe "map/reduce query with _temp_view in Javascript" do + before(:each) do + @db.bulk_save([ + {"beverage" => "beer", :count => 4}, + {"beverage" => "beer", :count => 2}, + {"beverage" => "tea", :count => 3} + ]) + end + it "should return the result of the temporary function" do + rs = @db.temp_view("function(doc){map(doc.beverage, doc.count)}", "function(beverage,counts){return sum(counts)}") + rs['result'].should == 9 + end + end + describe "select from an existing view" do before(:each) do r = @db.save({"_id" => "_design/first", "views" => {"test" => "function(doc){for(var w in doc){ if(!w.match(/^_/))map(w,doc[w])}}"}}) @@ -98,7 +112,6 @@ describe CouchRest::Database do lambda do @db.get('twoB') end.should raise_error(RestClient::Request::RequestFailed) - end end