converted to Hash subclass

This commit is contained in:
Chris Anderson 2008-10-02 10:45:08 -07:00
parent 2b7e49c9c6
commit 98923843ef
2 changed files with 286 additions and 311 deletions

View file

@ -8,8 +8,7 @@ module CouchRest
#
# This is an example class using CouchRest::Model. It is taken from the spec/couchrest/core/model_spec.rb file, which may be even more up to date than this example.
#
# class Article
# include CouchRest::Model
# class Article < CouchRest::Model
# use_database CouchRest.database!('http://localhost:5984/couchrest-model-test')
# unique_id :slug
#
@ -38,87 +37,26 @@ module CouchRest
#
# before(:create, :generate_slug_from_title)
# def generate_slug_from_title
# doc['slug'] = title.downcase.gsub(/[^a-z0-9]/,'-').squeeze('-').gsub(/^\-|\-$/,'')
# self['slug'] = title.downcase.gsub(/[^a-z0-9]/,'-').squeeze('-').gsub(/^\-|\-$/,'')
# end
# end
module Model
class << self
# this is the CouchRest::Database that model classes will use unless they override it with <tt>use_database</tt>
attr_accessor :default_database
end
# instance methods on the model classes
module InstanceMethods
attr_accessor :doc
class Model < Hash
# instantiates the hash by converting all the keys to strings.
def initialize keys = {}
self.doc = {}
super()
keys.each do |k,v|
doc[k.to_s] = v
self[k.to_s] = v
end
unless doc['_id'] && doc['_rev']
unless self['_id'] && self['_rev']
init_doc
end
end
# returns the database used by this model's class
def database
self.class.database
end
class << self
# this is the CouchRest::Database that model classes will use unless they override it with <tt>use_database</tt>
attr_accessor :default_database
# alias for doc['_id']
def id
doc['_id']
end
# alias for doc['_rev']
def rev
doc['_rev']
end
# returns true if the doc has never been saved
def new_record?
!doc['_rev']
end
# save the doc to the db using create or update
def save
if new_record?
create
else
update
end
end
protected
def create
set_unique_id if respond_to?(:set_unique_id) # hack
save_doc
end
def update
save_doc
end
private
def save_doc
result = database.save doc
if result['ok']
doc['_id'] = result['id']
doc['_rev'] = result['rev']
end
result['ok']
end
def init_doc
doc['type'] = self.class.to_s
end
end # module InstanceMethods
# Class methods for models that include CouchRest::Model
module ClassMethods
# override the CouchRest::Model-wide default_database
def use_database db
@database = db
@ -146,7 +84,7 @@ module CouchRest
keys.each do |method|
key = method.to_s
define_method "#{method}=" do |value|
doc[key] = value
self[key] = value
end
end
end
@ -156,7 +94,7 @@ module CouchRest
keys.each do |method|
key = method.to_s
define_method method do
doc[key]
self[key]
end
end
end
@ -164,24 +102,20 @@ module CouchRest
# Automatically set <tt>updated_at</tt> and <tt>created_at</tt> fields on the document whenever saving occurs. CouchRest uses a pretty decent time format by default. See Time#to_json
def timestamps!
before(:create) do
doc['updated_at'] = doc['created_at'] = Time.now
self['updated_at'] = self['created_at'] = Time.now
end
before(:update) do
doc['updated_at'] = Time.now
self['updated_at'] = Time.now
end
end
# Name a method that will be called before the document is first saved, which returns a string to be used for the document's <tt>_id</tt>. Because CouchDB enforces a constraint that each id must be unique, this can be used to enforce eg: uniq usernames. Note that this id must be globally unique across all document types which share a database, so if you'd like to scope uniqueness to this class, you should use the class name as part of the unique id.
def unique_id method
define_method :set_unique_id do
doc['_id'] ||= self.send(method)
self['_id'] ||= self.send(method)
end
end
end # module ClassMethods
module MagicViews
# Define a CouchDB view. The name of the view will be the concatenation of <tt>by</tt> and the keys joined by <tt>_and_</tt>
#
# ==== Example views:
@ -327,26 +261,67 @@ module CouchRest
@@design_doc_fresh = true
end
end # module MagicViews
end # class << self
module Callbacks
def self.included(model)
model.class_eval <<-EOS, __FILE__, __LINE__
include Extlib::Hook
# returns the database used by this model's class
def database
self.class.database
end
# alias for self['_id']
def id
self['_id']
end
# alias for self['_rev']
def rev
self['_rev']
end
# returns true if the self has never been saved
def new_record?
!rev
end
# save the doc to the db using create or update
def save
if new_record?
create
else
update
end
end
protected
def create
set_unique_id if respond_to?(:set_unique_id) # hack
save_doc
end
def update
save_doc
end
private
def save_doc
result = database.save self
if result['ok']
self['_id'] = result['id']
self['_rev'] = result['rev']
end
result['ok']
end
def init_doc
self['type'] = self.class.to_s
end
include ::Extlib::Hook
register_instance_hooks :save, :create, :update #, :destroy
EOS
end
end # module Callbacks
# bookkeeping section
# load the code into the model class
def self.included(model)
model.send(:include, InstanceMethods)
model.extend ClassMethods
model.extend MagicViews
model.send(:include, Callbacks)
end
end # module Model
end # class Model
end # module CouchRest

View file

@ -1,11 +1,10 @@
require File.dirname(__FILE__) + '/../../spec_helper'
class Basic
include CouchRest::Model
class Basic < CouchRest::Model
end
class Article
include CouchRest::Model
class Article < CouchRest::Model
use_database CouchRest.database!('http://localhost:5984/couchrest-model-test')
unique_id :slug
@ -34,7 +33,7 @@ class Article
before(:create, :generate_slug_from_title)
def generate_slug_from_title
doc['slug'] = title.downcase.gsub(/[^a-z0-9]/,'-').squeeze('-').gsub(/^\-|\-$/,'')
self['slug'] = title.downcase.gsub(/[^a-z0-9]/,'-').squeeze('-').gsub(/^\-|\-$/,'')
end
end
@ -61,6 +60,7 @@ describe CouchRest::Model do
describe "a new model" do
it "should be a new_record" do
@obj = Basic.new
@obj.rev.should be_nil
@obj.should be_a_new_record
end
end
@ -68,13 +68,13 @@ describe CouchRest::Model do
describe "a model with key_accessors" do
it "should allow reading keys" do
@art = Article.new
@art.doc['title'] = 'My Article Title'
@art['title'] = 'My Article Title'
@art.title.should == 'My Article Title'
end
it "should allow setting keys" do
@art = Article.new
@art.title = 'My Article Title'
@art.doc['title'].should == 'My Article Title'
@art['title'].should == 'My Article Title'
end
end
@ -83,7 +83,7 @@ describe CouchRest::Model do
@art = Article.new
t = Time.now
@art.date = t
@art.doc['date'].should == t
@art['date'].should == t
end
it "should not allow reading keys" do
@art = Article.new
@ -96,7 +96,7 @@ describe CouchRest::Model do
describe "a model with key_readers" do
it "should allow reading keys" do
@art = Article.new
@art.doc['slug'] = 'my-slug'
@art['slug'] = 'my-slug'
@art.slug.should == 'my-slug'
end
it "should not allow setting keys" do
@ -129,7 +129,7 @@ describe CouchRest::Model do
it "should be set for resaving" do
rev = @obj.rev
@obj.doc['another-key'] = "some value"
@obj['another-key'] = "some value"
@obj.save
@obj.rev.should_not == rev
end
@ -139,7 +139,7 @@ describe CouchRest::Model do
end
it "should set the type" do
@obj.doc['type'].should == 'Basic'
@obj['type'].should == 'Basic'
end
end
@ -254,7 +254,7 @@ describe CouchRest::Model do
end
it "should sort correctly" do
articles = Article.by_user_id_and_date
articles.collect{|a|a.doc['user_id']}.should == ['aaron', 'aaron', 'quentin', 'quentin']
articles.collect{|a|a['user_id']}.should == ['aaron', 'aaron', 'quentin', 'quentin']
articles[1].title.should == 'not junk'
end
it "should be queryable with couchrest options" do