require "net/http" require "enumerator" module CouchObject class View # # Takes: # * db as CouchObject::Database object or a string containing the database # uri and database name (http://localhost:5984/mydb) # * name (string). The name of the view # * query (JSON string). The JSON document that should be # added to the database # # Returns: # CouchObject::Reponse object instance # # Raises: # * an exeption if it can't figure out the database # def self.create(db, name, query) _db = self.get_db(db) # %2F => / _db.put("_design%2F#{name}", query) end # # Takes: # * db as CouchObject::Database object or a string containing the database # uri and database name (http://localhost:5984/mydb) # * name (string). The name of the view # # Returns: # new CouchObject::View instance # # Raises: # * an exeption if it can't figure out the database # def initialize(db, name) @db = self.class.get_db(db) @name = name end attr_accessor :db def name "_view/#{@name.dup}" end # # Returns an array of the rows returned by the view # # Takes: # * [+params+] (hash): a hash of URL query arguments supported # by couchDB. If omitted it defaults to not use a key # and to update the view. # # Example: # # view.query({:update => false, :key => "bar"}) => Array # # Returns: # * a array of rows from the view # # Raises: # * CouchObject::Errors::MissingView if the view doesn't exist # def query(params = {}) response = raw_query(params) rows_to_return = [] response["rows"].each do |params_for_object| rows_to_return << params_for_object["value"] end rows_to_return end # # Returns the response data from CouchDB for a view query without # # Takes: # * [+params+] (hash): a hash of URL query arguments supported # by couchDB. If omitted it defaults to not use a key # and to update the view. # # Example: # # view.raw_query({:update => false, :key => "bar"}) => data # # Returns: # * the response data for the view # # Raises: # * CouchObject::Errors::MissingView if the view doesn't exist # def raw_query(params = {}) #Create a querystring with the parameters passed inn querystring = "?" params.each_pair do |key, value| querystring += \ "#{key}=#{Utils.encode_querystring_parameter(value)}&" end querystring = querystring[0...-1] view_with_parameters = name + querystring response = JSON.parse(db.get(view_with_parameters).body) raise CouchObject::Errors::MissingView, \ "The view '#{name}' doesn't exist on the server" \ if response["error"] == "not_found" raise CouchObject::Errors::MapProcessError \ if response["error"] == "map_process_error" raise CouchObject::Errors::CouchDBError, \ "CouchDB returned and error and described the problem as #{response['reason']}" \ if response["error"] return response end def delete @db.delete("/#{db.name}/#{name}") end protected def self.get_db(db) case db.class.to_s when "CouchObject::Database" db when "String" CouchObject::Database.open(db) else raise "You have to supply a database URI " + \ "or a CouchObject::Database object" end end end end