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

@ -70,7 +70,14 @@ module CouchRest
# GET a document from CouchDB, by id. Returns a Ruby Hash.
def get 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
# GET an attachment directly from CouchDB
@ -103,7 +110,7 @@ module CouchRest
if doc['_attachments']
doc['_attachments'] = encode_attachments(doc['_attachments'])
end
if doc['_id']
result = if doc['_id']
slug = CGI.escape(doc['_id'])
CouchRest.put "#{@root}/#{slug}", doc
else
@ -114,6 +121,12 @@ module CouchRest
CouchRest.post @root, doc
end
end
if result['ok']
doc['_id'] = result['id']
doc['_rev'] = result['rev']
doc.database = self if doc.respond_to?(:database=)
end
result
end
# 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
# <tt>_rev</tt>.
def delete doc
raise ArgumentError, "_id and _rev required for deleting" unless doc['_id'] && doc['_rev']
slug = CGI.escape(doc['_id'])
CouchRest.delete "#{@root}/#{slug}?rev=#{doc['_rev']}"
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 'extlib'
require 'digest/md5'
require File.dirname(__FILE__) + '/document'
# = CouchRest::Model - ORM, the CouchDB way
module CouchRest
# = CouchRest::Model - ORM, the CouchDB way
@ -68,15 +68,12 @@ module CouchRest
#
# Article.by_tags :key => "ruby", :reduce => true
#
class Model < Hash
class Model < Document
# instantiates the hash by converting all the keys to strings.
def initialize keys = {}
super()
super(keys)
apply_defaults
keys.each do |k,v|
self[k.to_s] = v
end
cast_keys
unless self['_id'] && self['_rev']
self['couchrest-type'] = self.class.to_s
@ -90,7 +87,7 @@ module CouchRest
class_inheritable_accessor :casts
class_inheritable_accessor :default_obj
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_fresh
@ -114,14 +111,15 @@ module CouchRest
# Load all documents that have the "couchrest-type" field equal to the
# name of the current class. Take thes the standard set of
# CouchRest::Database#view options.
def all opts = {}
self.generated_design_doc ||= default_design_doc
def all opts = {}, &block
self.design_doc ||= Design.new(default_design_doc)
unless design_doc_fresh
refresh_design_doc
end
view_name = "#{design_doc_slug}/all"
raw = opts.delete(:raw)
fetch_view_with_docs(view_name, opts, raw)
# view_name = "#{design_doc_slug}/all"
# raw = opts.delete(:raw)
# fetch_view_with_docs(view_name, opts, raw)
view :all, opts, &block
end
# 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,
# it is recommended that you read the RSpec file at
# <tt>spec/core/model_spec.rb</tt>.
def view_by *keys
self.design_doc ||= Design.new(default_design_doc)
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
# if ducktype
# end
keys.push opts
self.design_doc.view_by(*keys)
self.design_doc_fresh = false
method_name
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
if opts = has_view?(m)
if has_view?(m)
query = args.shift || {}
view(m, opts.merge(query), *args)
view(m, query, *args)
else
super
end
@ -314,15 +327,14 @@ module CouchRest
# returns stored defaults if the there is a view named this in the design doc
def has_view?(view)
view = view.to_s
if generated_design_doc['views'][view]
generated_design_doc['views'][view]["couchrest-defaults"]
end
design_doc && design_doc['views'] && design_doc['views'][view]
end
# Fetch the generated design doc. Could raise an error if the generated views have not been queried yet.
def design_doc
database.get("_design/#{design_doc_slug}")
end
# # Fetch the generated design doc. Could raise an error if the generated
# # views have not been queried yet.
# def design_doc
# database.get("_design/#{design_doc_slug}")
# end
# Dispatches to any named view.
def view name, query={}, &block
@ -331,8 +343,7 @@ module CouchRest
end
query[:raw] = true if query[:reduce]
raw = query.delete(:raw)
view_name = "#{design_doc_slug}/#{name}"
fetch_view_with_docs(view_name, query, raw, &block)
fetch_view_with_docs(name, query, raw, &block)
end
private
@ -356,7 +367,7 @@ module CouchRest
def fetch_view view_name, opts, &block
retryable = true
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
rescue RestClient::ResourceNotFound => e
if retryable
@ -372,7 +383,7 @@ module CouchRest
def design_doc_slug
return design_doc_slug_cache if design_doc_slug_cache && design_doc_fresh
funcs = []
generated_design_doc['views'].each do |name, view|
design_doc['views'].each do |name, view|
funcs << "#{name}/#{view['map']}#{view['reduce']}"
end
md5 = Digest::MD5.hexdigest(funcs.sort.join(''))
@ -398,13 +409,15 @@ module CouchRest
did = "_design/#{design_doc_slug}"
saved = database.get(did) rescue nil
if saved
generated_design_doc['views'].each do |name, view|
design_doc['views'].each do |name, view|
saved['views'][name] = view
end
database.save(saved)
else
generated_design_doc['_id'] = did
database.save(generated_design_doc)
design_doc['_id'] = did
design_doc.delete('_rev')
design_doc.database = database
design_doc.save
end
self.design_doc_fresh = true
end
@ -416,16 +429,6 @@ module CouchRest
self.class.database
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
# for each key. Raises a NoMethodError if the corresponding methods are
# missing. In case of error, no attributes are changed.
@ -439,63 +442,40 @@ module CouchRest
save
end
# returns true if the document has never been saved
def new_record?
!rev
end
# for compatibility with old-school frameworks
alias :new_record? :new_document?
# 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
if new_record?
create
# We override this to create the create and update callback opportunities.
# I think we should drop those and just have save. If you care, in your callback,
# check new_document?
def save actually=false
if actually
super()
else
update
end
if new_document?
create
else
update
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
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
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
if self.class.default
self.class.default.each do |k,v|
self[k.to_s] = v
self[k] = v
end
end
end
@ -518,6 +498,8 @@ module CouchRest
end
include ::Extlib::Hook
# todo: drop create and update hooks...
# (use new_record? in callbacks if you care)
register_instance_hooks :save, :create, :update, :destroy
end # class Model

View file

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