Merge branch 'design-doc'

This commit is contained in:
Chris Anderson 2008-11-22 14:15:41 -08:00
commit e23ad9876e
11 changed files with 530 additions and 128 deletions

View file

@ -28,6 +28,9 @@ require 'couchrest/monkeypatches'
module CouchRest module CouchRest
autoload :Server, 'couchrest/core/server' autoload :Server, 'couchrest/core/server'
autoload :Database, 'couchrest/core/database' autoload :Database, 'couchrest/core/database'
autoload :Document, 'couchrest/core/document'
autoload :Design, 'couchrest/core/design'
autoload :View, 'couchrest/core/view'
autoload :Model, 'couchrest/core/model' autoload :Model, 'couchrest/core/model'
autoload :Pager, 'couchrest/helper/pager' autoload :Pager, 'couchrest/helper/pager'
autoload :FileManager, 'couchrest/helper/file_manager' autoload :FileManager, 'couchrest/helper/file_manager'

View file

@ -70,7 +70,14 @@ module CouchRest
# GET a document from CouchDB, by id. Returns a Ruby Hash. # GET a document from CouchDB, by id. Returns a Ruby Hash.
def get id def get id
slug = CGI.escape(id) slug = CGI.escape(id)
CouchRest.get "#{@root}/#{slug}" hash = CouchRest.get("#{@root}/#{slug}")
doc = if /^_design/ =~ hash["_id"]
Design.new(hash)
else
Document.new(hash)
end
doc.database = self
doc
end end
# GET an attachment directly from CouchDB # GET an attachment directly from CouchDB
@ -103,7 +110,7 @@ module CouchRest
if doc['_attachments'] if doc['_attachments']
doc['_attachments'] = encode_attachments(doc['_attachments']) doc['_attachments'] = encode_attachments(doc['_attachments'])
end end
if doc['_id'] result = if doc['_id']
slug = CGI.escape(doc['_id']) slug = CGI.escape(doc['_id'])
CouchRest.put "#{@root}/#{slug}", doc CouchRest.put "#{@root}/#{slug}", doc
else else
@ -114,6 +121,12 @@ module CouchRest
CouchRest.post @root, doc CouchRest.post @root, doc
end end
end end
if result['ok']
doc['_id'] = result['id']
doc['_rev'] = result['rev']
doc.database = self if doc.respond_to?(:database=)
end
result
end end
# POST an array of documents to CouchDB. If any of the documents are # POST an array of documents to CouchDB. If any of the documents are
@ -131,6 +144,8 @@ module CouchRest
# DELETE the document from CouchDB that has the given <tt>_id</tt> and # DELETE the document from CouchDB that has the given <tt>_id</tt> and
# <tt>_rev</tt>. # <tt>_rev</tt>.
def delete doc def delete doc
raise ArgumentError, "_id and _rev required for deleting" unless doc['_id'] && doc['_rev']
slug = CGI.escape(doc['_id']) slug = CGI.escape(doc['_id'])
CouchRest.delete "#{@root}/#{slug}?rev=#{doc['_rev']}" CouchRest.delete "#{@root}/#{slug}?rev=#{doc['_rev']}"
end end

View file

@ -0,0 +1,89 @@
module CouchRest
class Design < Document
def view_by *keys
opts = keys.pop if keys.last.is_a?(Hash)
opts ||= {}
self['views'] ||= {}
method_name = "by_#{keys.join('_and_')}"
if opts[:map]
view = {}
view['map'] = opts.delete(:map)
if opts[:reduce]
view['reduce'] = opts.delete(:reduce)
opts[:reduce] = false
end
self['views'][method_name] = view
else
doc_keys = keys.collect{|k|"doc['#{k}']"} # this is where :require => 'doc.x == true' would show up
key_emit = doc_keys.length == 1 ? "#{doc_keys.first}" : "[#{doc_keys.join(', ')}]"
guards = opts.delete(:guards) || []
guards.concat doc_keys
map_function = <<-JAVASCRIPT
function(doc) {
if (#{guards.join(' && ')}) {
emit(#{key_emit}, null);
}
}
JAVASCRIPT
self['views'][method_name] = {
'map' => map_function
}
end
self['views'][method_name]['couchrest-defaults'] = opts unless opts.empty?
method_name
end
# Dispatches to any named view.
def view view_name, query={}, &block
view_name = view_name.to_s
view_slug = "#{name}/#{view_name}"
defaults = (self['views'][view_name] && self['views'][view_name]["couchrest-defaults"]) || {}
fetch_view(view_slug, defaults.merge(query), &block)
end
def name
id.sub('_design/','') if id
end
def name= newname
self['_id'] = "_design/#{newname}"
end
def save
raise ArgumentError, "_design docs require a name" unless name && name.length > 0
super
end
private
# returns stored defaults if the there is a view named this in the design doc
def has_view?(view)
view = view.to_s
self['views'][view] &&
(self['views'][view]["couchrest-defaults"]||{})
end
# def fetch_view_with_docs name, opts, raw=false, &block
# if raw
# fetch_view name, opts, &block
# else
# begin
# view = fetch_view name, opts.merge({:include_docs => true}), &block
# view['rows'].collect{|r|new(r['doc'])} if view['rows']
# rescue
# # fallback for old versions of couchdb that don't
# # have include_docs support
# view = fetch_view name, opts, &block
# view['rows'].collect{|r|new(database.get(r['id']))} if view['rows']
# end
# end
# end
def fetch_view view_name, opts, &block
database.view(view_name, opts, &block)
end
end
end

View file

@ -0,0 +1,60 @@
module CouchRest
class Response < Hash
def initialize keys = {}
keys.each do |k,v|
self[k.to_s] = v
end
end
def []= key, value
super(key.to_s, value)
end
def [] key
super(key.to_s)
end
end
class Document < Response
attr_accessor :database
# alias for self['_id']
def id
self['_id']
end
# alias for self['_rev']
def rev
self['_rev']
end
# returns true if the document has never been saved
def new_document?
!rev
end
# Saves the document to the db using create or update. Also runs the :save
# callbacks. Sets the <tt>_id</tt> and <tt>_rev</tt> fields based on
# CouchDB's response.
def save
raise ArgumentError, "doc.database required for saving" unless database
result = database.save self
result['ok']
end
# Deletes the document from the database. Runs the :delete callbacks.
# Removes the <tt>_id</tt> and <tt>_rev</tt> fields, preparing the
# document to be saved to a new <tt>_id</tt>.
def destroy
raise ArgumentError, "doc.database required to destroy" unless database
result = database.delete self
if result['ok']
self['_rev'] = nil
self['_id'] = nil
end
result['ok']
end
end
end

View file

@ -1,7 +1,7 @@
require 'rubygems' require 'rubygems'
require 'extlib' require 'extlib'
require 'digest/md5' require 'digest/md5'
require File.dirname(__FILE__) + '/document'
# = CouchRest::Model - ORM, the CouchDB way # = CouchRest::Model - ORM, the CouchDB way
module CouchRest module CouchRest
# = CouchRest::Model - ORM, the CouchDB way # = CouchRest::Model - ORM, the CouchDB way
@ -68,15 +68,12 @@ module CouchRest
# #
# Article.by_tags :key => "ruby", :reduce => true # Article.by_tags :key => "ruby", :reduce => true
# #
class Model < Hash class Model < Document
# instantiates the hash by converting all the keys to strings. # instantiates the hash by converting all the keys to strings.
def initialize keys = {} def initialize keys = {}
super() super(keys)
apply_defaults apply_defaults
keys.each do |k,v|
self[k.to_s] = v
end
cast_keys cast_keys
unless self['_id'] && self['_rev'] unless self['_id'] && self['_rev']
self['couchrest-type'] = self.class.to_s self['couchrest-type'] = self.class.to_s
@ -90,7 +87,7 @@ module CouchRest
class_inheritable_accessor :casts class_inheritable_accessor :casts
class_inheritable_accessor :default_obj class_inheritable_accessor :default_obj
class_inheritable_accessor :class_database class_inheritable_accessor :class_database
class_inheritable_accessor :generated_design_doc class_inheritable_accessor :design_doc
class_inheritable_accessor :design_doc_slug_cache class_inheritable_accessor :design_doc_slug_cache
class_inheritable_accessor :design_doc_fresh class_inheritable_accessor :design_doc_fresh
@ -114,14 +111,15 @@ module CouchRest
# Load all documents that have the "couchrest-type" field equal to the # Load all documents that have the "couchrest-type" field equal to the
# name of the current class. Take thes the standard set of # name of the current class. Take thes the standard set of
# CouchRest::Database#view options. # CouchRest::Database#view options.
def all opts = {} def all opts = {}, &block
self.generated_design_doc ||= default_design_doc self.design_doc ||= Design.new(default_design_doc)
unless design_doc_fresh unless design_doc_fresh
refresh_design_doc refresh_design_doc
end end
view_name = "#{design_doc_slug}/all" # view_name = "#{design_doc_slug}/all"
raw = opts.delete(:raw) # raw = opts.delete(:raw)
fetch_view_with_docs(view_name, opts, raw) # fetch_view_with_docs(view_name, opts, raw)
view :all, opts, &block
end end
# Cast a field as another class. The class must be happy to have the # Cast a field as another class. The class must be happy to have the
@ -266,46 +264,61 @@ module CouchRest
# To understand the capabilities of this view system more compeletly, # To understand the capabilities of this view system more compeletly,
# it is recommended that you read the RSpec file at # it is recommended that you read the RSpec file at
# <tt>spec/core/model_spec.rb</tt>. # <tt>spec/core/model_spec.rb</tt>.
def view_by *keys def view_by *keys
self.design_doc ||= Design.new(default_design_doc)
opts = keys.pop if keys.last.is_a?(Hash) opts = keys.pop if keys.last.is_a?(Hash)
opts ||= {} opts ||= {}
type = self.to_s
method_name = "by_#{keys.join('_and_')}"
self.generated_design_doc ||= default_design_doc
ducktype = opts.delete(:ducktype) ducktype = opts.delete(:ducktype)
if opts[:map] # if ducktype
view = {} # end
view['map'] = opts.delete(:map) keys.push opts
if opts[:reduce] self.design_doc.view_by(*keys)
view['reduce'] = opts.delete(:reduce)
opts[:reduce] = false
end
generated_design_doc['views'][method_name] = view
else
doc_keys = keys.collect{|k|"doc['#{k}']"}
key_protection = doc_keys.join(' && ')
key_emit = doc_keys.length == 1 ? "#{doc_keys.first}" : "[#{doc_keys.join(', ')}]"
map_function = <<-JAVASCRIPT
function(doc) {
if (#{!ducktype ? "doc['couchrest-type'] == '#{type}' && " : ""}#{key_protection}) {
emit(#{key_emit}, null);
}
}
JAVASCRIPT
generated_design_doc['views'][method_name] = {
'map' => map_function
}
end
generated_design_doc['views'][method_name]['couchrest-defaults'] = opts
self.design_doc_fresh = false self.design_doc_fresh = false
method_name
end end
# def view_by *keys
# opts = keys.pop if keys.last.is_a?(Hash)
# opts ||= {}
#
#
# type = self.to_s
#
# method_name = "by_#{keys.join('_and_')}"
# self.generated_design_doc ||= default_design_doc
# ducktype = opts.delete(:ducktype)
# if opts[:map]
# view = {}
# view['map'] = opts.delete(:map)
# if opts[:reduce]
# view['reduce'] = opts.delete(:reduce)
# opts[:reduce] = false
# end
# generated_design_doc['views'][method_name] = view
# else
# doc_keys = keys.collect{|k|"doc['#{k}']"}
# key_protection = doc_keys.join(' && ')
# key_emit = doc_keys.length == 1 ? "#{doc_keys.first}" : "[#{doc_keys.join(', ')}]"
# map_function = <<-JAVASCRIPT
# function(doc) {
# if (#{!ducktype ? "doc['couchrest-type'] == '#{type}' && " : ""}#{key_protection}) {
# emit(#{key_emit}, null);
# }
# }
# JAVASCRIPT
# generated_design_doc['views'][method_name] = {
# 'map' => map_function
# }
# end
# generated_design_doc['views'][method_name]['couchrest-defaults'] = opts
# self.design_doc_fresh = false
# method_name
# end
def method_missing m, *args def method_missing m, *args
if opts = has_view?(m) if has_view?(m)
query = args.shift || {} query = args.shift || {}
view(m, opts.merge(query), *args) view(m, query, *args)
else else
super super
end end
@ -314,15 +327,14 @@ module CouchRest
# returns stored defaults if the there is a view named this in the design doc # returns stored defaults if the there is a view named this in the design doc
def has_view?(view) def has_view?(view)
view = view.to_s view = view.to_s
if generated_design_doc['views'][view] design_doc && design_doc['views'] && design_doc['views'][view]
generated_design_doc['views'][view]["couchrest-defaults"]
end
end end
# Fetch the generated design doc. Could raise an error if the generated views have not been queried yet. # # Fetch the generated design doc. Could raise an error if the generated
def design_doc # # views have not been queried yet.
database.get("_design/#{design_doc_slug}") # def design_doc
end # database.get("_design/#{design_doc_slug}")
# end
# Dispatches to any named view. # Dispatches to any named view.
def view name, query={}, &block def view name, query={}, &block
@ -331,8 +343,7 @@ module CouchRest
end end
query[:raw] = true if query[:reduce] query[:raw] = true if query[:reduce]
raw = query.delete(:raw) raw = query.delete(:raw)
view_name = "#{design_doc_slug}/#{name}" fetch_view_with_docs(name, query, raw, &block)
fetch_view_with_docs(view_name, query, raw, &block)
end end
private private
@ -356,7 +367,7 @@ module CouchRest
def fetch_view view_name, opts, &block def fetch_view view_name, opts, &block
retryable = true retryable = true
begin begin
database.view(view_name, opts, &block) design_doc.view(view_name, opts, &block)
# the design doc could have been deleted by a rouge process # the design doc could have been deleted by a rouge process
rescue RestClient::ResourceNotFound => e rescue RestClient::ResourceNotFound => e
if retryable if retryable
@ -372,7 +383,7 @@ module CouchRest
def design_doc_slug def design_doc_slug
return design_doc_slug_cache if design_doc_slug_cache && design_doc_fresh return design_doc_slug_cache if design_doc_slug_cache && design_doc_fresh
funcs = [] funcs = []
generated_design_doc['views'].each do |name, view| design_doc['views'].each do |name, view|
funcs << "#{name}/#{view['map']}#{view['reduce']}" funcs << "#{name}/#{view['map']}#{view['reduce']}"
end end
md5 = Digest::MD5.hexdigest(funcs.sort.join('')) md5 = Digest::MD5.hexdigest(funcs.sort.join(''))
@ -398,13 +409,15 @@ module CouchRest
did = "_design/#{design_doc_slug}" did = "_design/#{design_doc_slug}"
saved = database.get(did) rescue nil saved = database.get(did) rescue nil
if saved if saved
generated_design_doc['views'].each do |name, view| design_doc['views'].each do |name, view|
saved['views'][name] = view saved['views'][name] = view
end end
database.save(saved) database.save(saved)
else else
generated_design_doc['_id'] = did design_doc['_id'] = did
database.save(generated_design_doc) design_doc.delete('_rev')
design_doc.database = database
design_doc.save
end end
self.design_doc_fresh = true self.design_doc_fresh = true
end end
@ -416,16 +429,6 @@ module CouchRest
self.class.database self.class.database
end end
# alias for self['_id']
def id
self['_id']
end
# alias for self['_rev']
def rev
self['_rev']
end
# Takes a hash as argument, and applies the values by using writer methods # Takes a hash as argument, and applies the values by using writer methods
# for each key. Raises a NoMethodError if the corresponding methods are # for each key. Raises a NoMethodError if the corresponding methods are
# missing. In case of error, no attributes are changed. # missing. In case of error, no attributes are changed.
@ -439,63 +442,40 @@ module CouchRest
save save
end end
# returns true if the document has never been saved # for compatibility with old-school frameworks
def new_record? alias :new_record? :new_document?
!rev
end
# Saves the document to the db using create or update. Also runs the :save # We override this to create the create and update callback opportunities.
# callbacks. Sets the <tt>_id</tt> and <tt>_rev</tt> fields based on # I think we should drop those and just have save. If you care, in your callback,
# CouchDB's response. # check new_document?
def save def save actually=false
if new_record? if actually
create super()
else else
update if new_document?
end create
else
update
end
end
end end
# Deletes the document from the database. Runs the :delete callbacks.
# Removes the <tt>_id</tt> and <tt>_rev</tt> fields, preparing the
# document to be saved to a new <tt>_id</tt>.
def destroy
result = database.delete self
if result['ok']
self['_rev'] = nil
self['_id'] = nil
end
result['ok']
end
protected
# Saves a document for the first time, after running the before(:create)
# callbacks, and applying the unique_id.
def create
set_unique_id if respond_to?(:set_unique_id) # hack
save_doc
end
# Saves the document and runs the :update callbacks.
def update def update
save_doc save :actually
end
def create
# can we use the callbacks for this?
set_unique_id if self.respond_to?(:set_unique_id)
save :actually
end end
private private
def save_doc
result = database.save self
if result['ok']
self['_id'] = result['id']
self['_rev'] = result['rev']
end
result['ok']
end
def apply_defaults def apply_defaults
if self.class.default if self.class.default
self.class.default.each do |k,v| self.class.default.each do |k,v|
self[k.to_s] = v self[k] = v
end end
end end
end end
@ -518,6 +498,8 @@ module CouchRest
end end
include ::Extlib::Hook include ::Extlib::Hook
# todo: drop create and update hooks...
# (use new_record? in callbacks if you care)
register_instance_hooks :save, :create, :update, :destroy register_instance_hooks :save, :create, :update, :destroy
end # class Model end # class Model

View file

@ -0,0 +1,4 @@
module CouchRest
class View
end
end

View file

@ -215,7 +215,7 @@ describe CouchRest::Database do
r2["lemons"].should == "from texas" r2["lemons"].should == "from texas"
end end
it "should use PUT with UUIDs" do it "should use PUT with UUIDs" do
CouchRest.should_receive(:put) CouchRest.should_receive(:put).and_return({"ok" => true, "id" => "100", "rev" => "55"})
r = @db.save({'just' => ['another document']}) r = @db.save({'just' => ['another document']})
end end
@ -418,6 +418,9 @@ describe CouchRest::Database do
@db.delete doc @db.delete doc
lambda{@db.get @docid}.should raise_error lambda{@db.get @docid}.should raise_error
end end
it "should fail without an _id" do
lambda{@db.delete({"not"=>"a real doc"})}.should raise_error(ArgumentError)
end
end end
it "should list documents" do it "should list documents" do

View file

@ -0,0 +1,131 @@
require File.dirname(__FILE__) + '/../../spec_helper'
describe CouchRest::Design do
describe "defining a view" do
it "should add a view to the design doc" do
@des = CouchRest::Design.new
method = @des.view_by :name
method.should == "by_name"
@des["views"]["by_name"].should_not be_nil
end
end
describe "with an unsaved view" do
before(:each) do
@des = CouchRest::Design.new
method = @des.view_by :name
end
it "should accept a name" do
@des.name = "mytest"
@des.name.should == "mytest"
end
it "should not save on view definition" do
@des.rev.should be_nil
end
it "should freak out on view access" do
lambda{@des.view :by_name}.should raise_error
end
end
describe "saving" do
before(:each) do
@des = CouchRest::Design.new
method = @des.view_by :name
@des.database = reset_test_db!
end
it "should fail without a name" do
lambda{@des.save}.should raise_error(ArgumentError)
end
it "should work with a name" do
@des.name = "myview"
@des.save
end
end
describe "when it's saved" do
before(:each) do
@db = reset_test_db!
@db.bulk_save([{"name" => "x"},{"name" => "y"}])
@des = CouchRest::Design.new
@des.database = @db
method = @des.view_by :name
end
it "should by queryable when it's saved" do
@des.name = "mydesign"
@des.save
res = @des.view :by_name
res["rows"][0]["key"].should == "x"
end
end
describe "from a saved document" do
before(:all) do
@db = reset_test_db!
@db.save({
"_id" => "_design/test",
"views" => {
"by_name" => {
"map" => "function(doc){if (doc.name) emit(doc.name, null)}"
}
}
})
@db.bulk_save([{"name" => "a"},{"name" => "b"}])
@des = @db.get "_design/test"
end
it "should be a Design" do
@des.should be_an_instance_of CouchRest::Design
end
it "should have a modifiable name" do
@des.name.should == "test"
@des.name = "supertest"
@des.id.should == "_design/supertest"
end
it "should by queryable" do
res = @des.view :by_name
res["rows"][0]["key"].should == "a"
end
end
describe "a view with default options" do
before(:all) do
@db = reset_test_db!
@des = CouchRest::Design.new
@des.name = "test"
method = @des.view_by :name, :descending => true
@des.database = @db
@des.save
@db.bulk_save([{"name" => "a"},{"name" => "z"}])
end
it "should save them" do
@d2 = @db.get(@des.id)
@d2["views"]["by_name"]["couchrest-defaults"].should == {"descending"=>true}
end
it "should use them" do
res = @des.view :by_name
res["rows"].first["key"].should == "z"
end
it "should override them" do
res = @des.view :by_name, :descending => false
res["rows"].first["key"].should == "a"
end
end
describe "a view with multiple keys" do
before(:all) do
@db = reset_test_db!
@des = CouchRest::Design.new
@des.name = "test"
method = @des.view_by :name, :age
@des.database = @db
@des.save
@db.bulk_save([{"name" => "a", "age" => 2},
{"name" => "a", "age" => 4},{"name" => "z", "age" => 9}])
end
it "should work" do
res = @des.view :by_name_and_age
res["rows"].first["key"].should == ["a",2]
end
end
end

View file

@ -0,0 +1,96 @@
require File.dirname(__FILE__) + '/../../spec_helper'
describe CouchRest::Document, "[]=" do
before(:each) do
@doc = CouchRest::Document.new
end
it "should work" do
@doc["enamel"].should == nil
@doc["enamel"] = "Strong"
@doc["enamel"].should == "Strong"
end
it "[]= should convert to string" do
@doc["enamel"].should == nil
@doc[:enamel] = "Strong"
@doc["enamel"].should == "Strong"
end
it "should read as a string" do
@doc[:enamel] = "Strong"
@doc[:enamel].should == "Strong"
end
end
describe CouchRest::Document, "new" do
before(:each) do
@doc = CouchRest::Document.new("key" => [1,2,3], :more => "values")
end
it "should create itself from a Hash" do
@doc["key"].should == [1,2,3]
@doc["more"].should == "values"
end
it "should not have rev and id" do
@doc.rev.should be_nil
@doc.id.should be_nil
end
it "should freak out when saving without a database" do
lambda{@doc.save}.should raise_error(ArgumentError)
end
end
# move to database spec
describe CouchRest::Document, "saving using a database" do
before(:all) do
@doc = CouchRest::Document.new("key" => [1,2,3], :more => "values")
@db = reset_test_db!
@resp = @db.save(@doc)
end
it "should apply the database" do
@doc.database.should == @db
end
it "should get id and rev" do
@doc.id.should == @resp["id"]
@doc.rev.should == @resp["rev"]
end
end
describe "getting from a database" do
before(:all) do
@db = reset_test_db!
@resp = @db.save({
"key" => "value"
})
@doc = @db.get @resp['id']
end
it "should return a document" do
@doc.should be_an_instance_of(CouchRest::Document)
end
it "should have a database" do
@doc.database.should == @db
end
it "should be saveable and resavable" do
@doc["more"] = "keys"
@doc.save
@db.get(@resp['id'])["more"].should == "keys"
@doc["more"] = "these keys"
@doc.save
@db.get(@resp['id'])["more"].should == "these keys"
end
end
describe "destroying a document from a db" do
before(:all) do
@db = reset_test_db!
@resp = @db.save({
"key" => "value"
})
@doc = @db.get @resp['id']
end
it "should make it disappear" do
@doc.destroy
lambda{@db.get @resp['id']}.should raise_error
end
it "should error when there's no db" do
@doc = CouchRest::Document.new("key" => [1,2,3], :more => "values")
lambda{@doc.destroy}.should raise_error(ArgumentError)
end
end

View file

@ -16,6 +16,7 @@ end
class Question < CouchRest::Model class Question < CouchRest::Model
key_accessor :q, :a key_accessor :q, :a
couchrest_type = 'Question'
end end
class Person < CouchRest::Model class Person < CouchRest::Model
@ -213,7 +214,7 @@ describe CouchRest::Model do
@course["questions"][0].a[0].should == "beast" @course["questions"][0].a[0].should == "beast"
end end
end end
describe "finding all instances of a model" do describe "finding all instances of a model" do
before(:all) do before(:all) do
WithTemplate.new('important-field' => '1').save WithTemplate.new('important-field' => '1').save
@ -285,6 +286,11 @@ describe CouchRest::Model do
Article.database.delete(@old) if @old Article.database.delete(@old) if @old
end end
it "should be a new document" do
@art.should be_a_new_document
@art.title.should be_nil
end
it "should require the title" do it "should require the title" do
lambda{@art.save}.should raise_error lambda{@art.save}.should raise_error
@art.title = 'This is the title' @art.title = 'This is the title'
@ -390,10 +396,14 @@ describe CouchRest::Model do
written_at += 24 * 3600 written_at += 24 * 3600
end end
end end
it "should have a design doc" do
Article.design_doc["views"]["by_date"].should_not be_nil
end
it "should create the design doc" do it "should save the design doc" do
Article.by_date rescue nil Article.by_date #rescue nil
doc = Article.design_doc doc = Article.database.get Article.design_doc.id
doc['views']['by_date'].should_not be_nil doc['views']['by_date'].should_not be_nil
end end
@ -402,7 +412,7 @@ describe CouchRest::Model do
view['rows'].length.should == 4 view['rows'].length.should == 4
end end
it "should return the matching objects (with descending)" do it "should return the matching objects (with default argument :descending => true)" do
articles = Article.by_date articles = Article.by_date
articles.collect{|a|a.title}.should == @titles.reverse articles.collect{|a|a.title}.should == @titles.reverse
end end
@ -417,10 +427,9 @@ describe CouchRest::Model do
before(:all) do before(:all) do
Course.database.delete! rescue nil Course.database.delete! rescue nil
@db = @cr.create_db(TESTDB) rescue nil @db = @cr.create_db(TESTDB) rescue nil
Course.new(:title => 'aaa').save %w{aaa bbb ddd eee}.each do |title|
Course.new(:title => 'bbb').save Course.new(:title => title).save
Course.new(:title => 'ddd').save end
Course.new(:title => 'eee').save
end end
it "should make the design doc upon first query" do it "should make the design doc upon first query" do
Course.by_title Course.by_title
@ -442,13 +451,12 @@ describe CouchRest::Model do
courses = [] courses = []
rs = Course.by_title # remove me rs = Course.by_title # remove me
Course.view(:by_title) do |course| Course.view(:by_title) do |course|
# puts "course"
courses << course courses << course
end end
# courses.should == 'x'
courses[0]["doc"]["title"].should =='aaa' courses[0]["doc"]["title"].should =='aaa'
end end
end end
describe "a ducktype view" do describe "a ducktype view" do
before(:all) do before(:all) do
@ -527,6 +535,7 @@ describe CouchRest::Model do
end end
end end
# TODO: moved to Design, delete
describe "adding a view" do describe "adding a view" do
before(:each) do before(:each) do
Article.by_date Article.by_date
@ -544,6 +553,8 @@ describe CouchRest::Model do
Article.by_updated_at Article.by_updated_at
newdocs = Article.database.documents :startkey => "_design/", newdocs = Article.database.documents :startkey => "_design/",
:endkey => "_design/\u9999" :endkey => "_design/\u9999"
# puts @design_docs.inspect
# puts newdocs.inspect
newdocs["rows"].length.should == @design_docs["rows"].length + 1 newdocs["rows"].length.should == @design_docs["rows"].length + 1
end end
end end

View file

@ -3,4 +3,12 @@ require File.dirname(__FILE__) + '/../lib/couchrest'
FIXTURE_PATH = File.dirname(__FILE__) + '/fixtures' FIXTURE_PATH = File.dirname(__FILE__) + '/fixtures'
COUCHHOST = "http://localhost:5984" COUCHHOST = "http://localhost:5984"
TESTDB = 'couchrest-test' TESTDB = 'couchrest-test'
def reset_test_db!
cr = CouchRest.new(COUCHHOST)
db = cr.database(TESTDB)
db.delete! rescue nil
db = cr.create_db(TESTDB) rescue nin
db
end