Updated website to reflect proper git repo path
[couchobject.git] / bin / couch_ruby_view_requestor
blob3dafac2071f0e9ecc2a480e271068203c5f6a642
1 #!/usr/bin/env ruby -wKU
3 require 'rubygems'
4 require 'json'
6 # Highly experimental view requestor for CouchDb
7 #
8 # >> pp db.post("_temp_view", "proc{|doc| if doc['foo'] =~ /ba/; return doc;end }")
9 # #<CouchObject::Response:0x616944
10 # @parsed_body=
11 # {"rows"=>
12 # [{"_rev"=>928806717,
13 # "_id"=>"28D568C5992CBD2B4711F57225A19517",
14 # "value"=>
15 # {"_id"=>"28D568C5992CBD2B4711F57225A19517",
16 # "_rev"=>928806717,
17 # "foo"=>"baz"}},
18 # {"_rev"=>-1696868121,
19 # "_id"=>"601D858DB2E298EFC4BBA92A11760D1E",
20 # "value"=>
21 # {"_id"=>"601D858DB2E298EFC4BBA92A11760D1E",
22 # "_rev"=>-1696868121,
23 # "foo"=>"bar"}},
24 # {"_rev"=>-2093091288,
25 # "_id"=>"CABCEB3F2C8B70B3FE24A03FF6AB7A1E",
26 # "value"=>
27 # {"_id"=>"CABCEB3F2C8B70B3FE24A03FF6AB7A1E",
28 # "_rev"=>-2093091288,
29 # "foo"=>"bar"}}],
30 # "offset"=>0,
31 # "total_rows"=>3,
32 # "view"=>"_temp_view:proc{|doc| if doc['foo'] =~ /ba/; return doc;end }"},
33 # @response=#<Net::HTTPOK 200 OK readbody=true>>
35 $callables = []
37 while cmd = ARGF.gets
38 #$stderr.puts "@@@==> got: #{cmd.inspect}"
39 cmd = JSON.parse(cmd)
40 case cmd[0]
41 when "reset"
42 $callables = []
43 puts "true"
44 STDOUT.flush
45 when "add_map_fun"
46 # second arg is a string that will compile to a function
47 callable = eval(cmd[1])
48 if callable.respond_to?(:call)
49 $callables << callable
50 puts "true"
51 else
52 puts JSON.unparse(["error", "String must respond_to #call, eg proc{|doc| doc.title == 'foo' }"])
53 end
54 STDOUT.flush
55 when "map_doc"
56 results = []
57 doc = cmd[1]
58 doc.freeze
59 $callables.each do |callable|
60 begin
61 result = callable.call(doc)
62 if result.nil?
63 results << 0 # indicate no match
64 elsif result == 0 # not sure if this one is correct
65 results << {"value"=>0}
66 else
67 results << result
68 end
69 rescue => e
70 # An error mapping the document. Indicate no match.
71 results << 0
72 end
73 end
74 puts JSON.unparse(results)
75 STDOUT.flush
76 else
77 puts "error"
78 STDOUT.flush
79 exit(1)
80 end
81 end