ability to set keys and count on temp_views

This commit is contained in:
Chris Anderson 2008-05-22 21:57:21 -07:00
parent ce5bf9ffe8
commit ea68f7af85
3 changed files with 29 additions and 11 deletions

View file

@ -53,6 +53,17 @@ class CouchRest
def delete uri def delete uri
JSON.parse(RestClient.delete(uri)) JSON.parse(RestClient.delete(uri))
end end
def paramify_url url, params = nil
if params
query = params.collect do |k,v|
v = JSON.unparse(v) if %w{key startkey endkey}.include?(k.to_s)
"#{k}=#{CGI.escape(v.to_s)}"
end.join("&")
url = "#{url}?#{query}"
end
url
end
end end
end end

View file

@ -13,19 +13,13 @@ class CouchRest
CouchRest.get "#{@root}/_all_docs" CouchRest.get "#{@root}/_all_docs"
end end
def temp_view funcs, type = 'application/json' def temp_view funcs, params = nil
JSON.parse(RestClient.post("#{@root}/_temp_view", JSON.unparse(funcs), {"Content-Type" => type})) url = CouchRest.paramify_url "#{@root}/_temp_view", params
JSON.parse(RestClient.post(url, JSON.unparse(funcs), {"Content-Type" => 'application/json'}))
end end
def view name, params = nil def view name, params = nil
url = "#{@root}/_view/#{name}" url = CouchRest.paramify_url "#{@root}/_view/#{name}", params
if params
query = params.collect do |k,v|
v = JSON.unparse(v) if %w{key startkey endkey}.include?(k.to_s)
"#{k}=#{CGI.escape(v.to_s)}"
end.join("&")
url = "#{url}?#{query}"
end
CouchRest.get url CouchRest.get url
end end

View file

@ -23,11 +23,24 @@ describe CouchRest::Database do
{"mild" => "yet local"}, {"mild" => "yet local"},
{"another" => ["set","of","keys"]} {"another" => ["set","of","keys"]}
]) ])
@temp_view = {:map => "function(doc){for(var w in doc){ if(!w.match(/^_/))emit(w,doc[w])}}"}
end end
it "should return the result of the temporary function" do it "should return the result of the temporary function" do
rs = @db.temp_view(:map => "function(doc){for(var w in doc){ if(!w.match(/^_/))emit(w,doc[w])}}") rs = @db.temp_view(@temp_view)
rs['rows'].select{|r|r['key'] == 'wild' && r['value'] == 'and random'}.length.should == 1 rs['rows'].select{|r|r['key'] == 'wild' && r['value'] == 'and random'}.length.should == 1
end end
it "should work with a range" do
rs = @db.temp_view(@temp_view,{:startkey => "b", :endkey => "z"})
rs['rows'].length.should == 2
end
it "should work with a key" do
rs = @db.temp_view(@temp_view,{:key => "wild"})
rs['rows'].length.should == 1
end
it "should work with a count" do
rs = @db.temp_view(@temp_view,{:count => 1})
rs['rows'].length.should == 1
end
end end
describe "map/reduce query with _temp_view in Javascript" do describe "map/reduce query with _temp_view in Javascript" do