fix indentation
This commit is contained in:
parent
8ac6b78170
commit
8cfed5af4f
1 changed files with 245 additions and 241 deletions
|
@ -62,268 +62,272 @@ module CouchRest
|
||||||
init_doc
|
init_doc
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
class << self
|
class << self
|
||||||
# this is the CouchRest::Database that model classes will use unless
|
# this is the CouchRest::Database that model classes will use unless
|
||||||
# they override it with <tt>use_database</tt>
|
# they override it with <tt>use_database</tt>
|
||||||
attr_accessor :default_database
|
attr_accessor :default_database
|
||||||
attr_accessor :template
|
attr_accessor :template
|
||||||
|
|
||||||
# override the CouchRest::Model-wide default_database
|
# override the CouchRest::Model-wide default_database
|
||||||
def use_database db
|
def use_database db
|
||||||
@database = db
|
@database = db
|
||||||
end
|
end
|
||||||
|
|
||||||
# returns the CouchRest::Database instance that this class uses
|
# returns the CouchRest::Database instance that this class uses
|
||||||
def database
|
def database
|
||||||
@database || CouchRest::Model.default_database
|
@database || CouchRest::Model.default_database
|
||||||
end
|
end
|
||||||
|
|
||||||
# load a document from the database
|
# load a document from the database
|
||||||
def get id
|
def get id
|
||||||
doc = database.get id
|
doc = database.get id
|
||||||
new(doc)
|
new(doc)
|
||||||
end
|
end
|
||||||
|
|
||||||
# Defines methods for reading and writing from fields in the document.
|
def cast field, opts = {}
|
||||||
# Uses key_writer and key_reader internally.
|
|
||||||
def key_accessor *keys
|
end
|
||||||
key_writer *keys
|
|
||||||
key_reader *keys
|
|
||||||
end
|
|
||||||
|
|
||||||
# For each argument key, define a method <tt>key=</tt> that sets the
|
# Defines methods for reading and writing from fields in the document.
|
||||||
# corresponding field on the CouchDB document.
|
# Uses key_writer and key_reader internally.
|
||||||
def key_writer *keys
|
def key_accessor *keys
|
||||||
keys.each do |method|
|
key_writer *keys
|
||||||
key = method.to_s
|
key_reader *keys
|
||||||
define_method "#{method}=" do |value|
|
end
|
||||||
self[key] = value
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# For each argument key, define a method <tt>key</tt> that reads the
|
# For each argument key, define a method <tt>key=</tt> that sets the
|
||||||
# corresponding field on the CouchDB document.
|
# corresponding field on the CouchDB document.
|
||||||
def key_reader *keys
|
def key_writer *keys
|
||||||
keys.each do |method|
|
keys.each do |method|
|
||||||
key = method.to_s
|
key = method.to_s
|
||||||
define_method method do
|
define_method "#{method}=" do |value|
|
||||||
self[key]
|
self[key] = value
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
def default
|
|
||||||
@default
|
|
||||||
end
|
|
||||||
|
|
||||||
def set_default hash
|
|
||||||
@default = hash
|
|
||||||
end
|
|
||||||
|
|
||||||
# Automatically set <tt>updated_at</tt> and <tt>created_at</tt> fields
|
# For each argument key, define a method <tt>key</tt> that reads the
|
||||||
# on the document whenever saving occurs. CouchRest uses a pretty
|
# corresponding field on the CouchDB document.
|
||||||
# decent time format by default. See Time#to_json
|
def key_reader *keys
|
||||||
def timestamps!
|
keys.each do |method|
|
||||||
before(:create) do
|
key = method.to_s
|
||||||
self['updated_at'] = self['created_at'] = Time.now
|
define_method method do
|
||||||
end
|
self[key]
|
||||||
before(:update) do
|
end
|
||||||
self['updated_at'] = Time.now
|
end
|
||||||
end
|
end
|
||||||
end
|
|
||||||
|
|
||||||
# Name a method that will be called before the document is first saved,
|
def default
|
||||||
# which returns a string to be used for the document's <tt>_id</tt>.
|
@default
|
||||||
# Because CouchDB enforces a constraint that each id must be unique,
|
end
|
||||||
# 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 = nil, &block
|
|
||||||
if method
|
|
||||||
define_method :set_unique_id do
|
|
||||||
self['_id'] ||= self.send(method)
|
|
||||||
end
|
|
||||||
elsif block
|
|
||||||
define_method :set_unique_id do
|
|
||||||
uniqid = block.call(self)
|
|
||||||
raise ArgumentError, "unique_id block must not return nil" if uniqid.nil?
|
|
||||||
self['_id'] ||= uniqid
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# 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:
|
|
||||||
#
|
|
||||||
# class Post
|
|
||||||
# # view with default options
|
|
||||||
# # query with Post.by_date
|
|
||||||
# view_by :date, :descending => true
|
|
||||||
#
|
|
||||||
# # view with compound sort-keys
|
|
||||||
# # query with Post.by_user_id_and_date
|
|
||||||
# view_by :user_id, :date
|
|
||||||
#
|
|
||||||
# # view with custom map/reduce functions
|
|
||||||
# # query with Post.by_tags :reduce => true
|
|
||||||
# view_by :tags,
|
|
||||||
# :map =>
|
|
||||||
# "function(doc) {
|
|
||||||
# if (doc.type == 'Post' && doc.tags) {
|
|
||||||
# doc.tags.forEach(function(tag){
|
|
||||||
# emit(doc.tag, 1);
|
|
||||||
# });
|
|
||||||
# }
|
|
||||||
# }",
|
|
||||||
# :reduce =>
|
|
||||||
# "function(keys, values, rereduce) {
|
|
||||||
# return sum(values);
|
|
||||||
# }"
|
|
||||||
# end
|
|
||||||
#
|
|
||||||
# <tt>view_by :date</tt> will create a view defined by this Javascript
|
|
||||||
# function:
|
|
||||||
#
|
|
||||||
# function(doc) {
|
|
||||||
# if (doc.type == 'Post' && doc.date) {
|
|
||||||
# emit(doc.date, null);
|
|
||||||
# }
|
|
||||||
# }
|
|
||||||
#
|
|
||||||
# It can be queried by calling <tt>Post.by_date</tt> which accepts all
|
|
||||||
# valid options for CouchRest::Database#view. In addition, calling with
|
|
||||||
# the <tt>:raw => true</tt> option will return the view rows
|
|
||||||
# themselves. By default <tt>Post.by_date</tt> will return the
|
|
||||||
# documents included in the generated view.
|
|
||||||
#
|
|
||||||
# CouchRest::Database#view options can be applied at view definition
|
|
||||||
# time as defaults, and they will be curried and used at view query
|
|
||||||
# time. Or they can be overridden at query time.
|
|
||||||
#
|
|
||||||
# Custom views can be queried with <tt>:reduce => true</tt> to return
|
|
||||||
# reduce results. The default for custom views is to query with
|
|
||||||
# <tt>:reduce => false</tt>.
|
|
||||||
#
|
|
||||||
# Views are generated (on a per-model basis) lazily on first-access.
|
|
||||||
# This means that if you are deploying changes to a view, the views for
|
|
||||||
# that model won't be available until generation is complete. This can
|
|
||||||
# take some time with large databases. Strategies are in the works.
|
|
||||||
#
|
|
||||||
# To understand the capabilities of this view system more compeletly,
|
|
||||||
# it is recommended that you read the RSpec file at
|
|
||||||
# <tt>spec/core/model.rb</tt>.
|
|
||||||
def view_by *keys
|
|
||||||
opts = keys.pop if keys.last.is_a?(Hash)
|
|
||||||
opts ||= {}
|
|
||||||
type = self.to_s
|
|
||||||
|
|
||||||
method_name = "by_#{keys.join('_and_')}"
|
def set_default hash
|
||||||
@@design_doc ||= default_design_doc
|
@default = hash
|
||||||
|
end
|
||||||
|
|
||||||
if opts[:map]
|
# Automatically set <tt>updated_at</tt> and <tt>created_at</tt> fields
|
||||||
view = {}
|
# on the document whenever saving occurs. CouchRest uses a pretty
|
||||||
view['map'] = opts.delete(:map)
|
# decent time format by default. See Time#to_json
|
||||||
if opts[:reduce]
|
def timestamps!
|
||||||
view['reduce'] = opts.delete(:reduce)
|
before(:create) do
|
||||||
opts[:reduce] = false
|
self['updated_at'] = self['created_at'] = Time.now
|
||||||
end
|
end
|
||||||
@@design_doc['views'][method_name] = view
|
before(:update) do
|
||||||
else
|
self['updated_at'] = Time.now
|
||||||
doc_keys = keys.collect{|k|"doc['#{k}']"}
|
end
|
||||||
key_protection = doc_keys.join(' && ')
|
end
|
||||||
key_emit = doc_keys.length == 1 ? "#{doc_keys.first}" : "[#{doc_keys.join(', ')}]"
|
|
||||||
map_function = <<-JAVASCRIPT
|
|
||||||
function(doc) {
|
|
||||||
if (doc.type == '#{type}' && #{key_protection}) {
|
|
||||||
emit(#{key_emit}, null);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
JAVASCRIPT
|
|
||||||
@@design_doc['views'][method_name] = {
|
|
||||||
'map' => map_function
|
|
||||||
}
|
|
||||||
end
|
|
||||||
|
|
||||||
@@design_doc_fresh = false
|
# 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 = nil, &block
|
||||||
|
if method
|
||||||
|
define_method :set_unique_id do
|
||||||
|
self['_id'] ||= self.send(method)
|
||||||
|
end
|
||||||
|
elsif block
|
||||||
|
define_method :set_unique_id do
|
||||||
|
uniqid = block.call(self)
|
||||||
|
raise ArgumentError, "unique_id block must not return nil" if uniqid.nil?
|
||||||
|
self['_id'] ||= uniqid
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
self.meta_class.instance_eval do
|
# Define a CouchDB view. The name of the view will be the concatenation
|
||||||
define_method method_name do |*args|
|
# of <tt>by</tt> and the keys joined by <tt>_and_</tt>
|
||||||
query = opts.merge(args[0] || {})
|
#
|
||||||
query[:raw] = true if query[:reduce]
|
# ==== Example views:
|
||||||
unless @@design_doc_fresh
|
#
|
||||||
refresh_design_doc
|
# class Post
|
||||||
end
|
# # view with default options
|
||||||
raw = query.delete(:raw)
|
# # query with Post.by_date
|
||||||
view_name = "#{type}/#{method_name}"
|
# view_by :date, :descending => true
|
||||||
|
#
|
||||||
|
# # view with compound sort-keys
|
||||||
|
# # query with Post.by_user_id_and_date
|
||||||
|
# view_by :user_id, :date
|
||||||
|
#
|
||||||
|
# # view with custom map/reduce functions
|
||||||
|
# # query with Post.by_tags :reduce => true
|
||||||
|
# view_by :tags,
|
||||||
|
# :map =>
|
||||||
|
# "function(doc) {
|
||||||
|
# if (doc.type == 'Post' && doc.tags) {
|
||||||
|
# doc.tags.forEach(function(tag){
|
||||||
|
# emit(doc.tag, 1);
|
||||||
|
# });
|
||||||
|
# }
|
||||||
|
# }",
|
||||||
|
# :reduce =>
|
||||||
|
# "function(keys, values, rereduce) {
|
||||||
|
# return sum(values);
|
||||||
|
# }"
|
||||||
|
# end
|
||||||
|
#
|
||||||
|
# <tt>view_by :date</tt> will create a view defined by this Javascript
|
||||||
|
# function:
|
||||||
|
#
|
||||||
|
# function(doc) {
|
||||||
|
# if (doc.type == 'Post' && doc.date) {
|
||||||
|
# emit(doc.date, null);
|
||||||
|
# }
|
||||||
|
# }
|
||||||
|
#
|
||||||
|
# It can be queried by calling <tt>Post.by_date</tt> which accepts all
|
||||||
|
# valid options for CouchRest::Database#view. In addition, calling with
|
||||||
|
# the <tt>:raw => true</tt> option will return the view rows
|
||||||
|
# themselves. By default <tt>Post.by_date</tt> will return the
|
||||||
|
# documents included in the generated view.
|
||||||
|
#
|
||||||
|
# CouchRest::Database#view options can be applied at view definition
|
||||||
|
# time as defaults, and they will be curried and used at view query
|
||||||
|
# time. Or they can be overridden at query time.
|
||||||
|
#
|
||||||
|
# Custom views can be queried with <tt>:reduce => true</tt> to return
|
||||||
|
# reduce results. The default for custom views is to query with
|
||||||
|
# <tt>:reduce => false</tt>.
|
||||||
|
#
|
||||||
|
# Views are generated (on a per-model basis) lazily on first-access.
|
||||||
|
# This means that if you are deploying changes to a view, the views for
|
||||||
|
# that model won't be available until generation is complete. This can
|
||||||
|
# take some time with large databases. Strategies are in the works.
|
||||||
|
#
|
||||||
|
# To understand the capabilities of this view system more compeletly,
|
||||||
|
# it is recommended that you read the RSpec file at
|
||||||
|
# <tt>spec/core/model.rb</tt>.
|
||||||
|
def view_by *keys
|
||||||
|
opts = keys.pop if keys.last.is_a?(Hash)
|
||||||
|
opts ||= {}
|
||||||
|
type = self.to_s
|
||||||
|
|
||||||
view = fetch_view(view_name, query)
|
method_name = "by_#{keys.join('_and_')}"
|
||||||
if raw
|
@@design_doc ||= default_design_doc
|
||||||
view
|
|
||||||
else
|
|
||||||
# TODO this can be optimized once the include-docs patch is applied
|
|
||||||
view['rows'].collect{|r|new(database.get(r['id']))}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
private
|
if opts[:map]
|
||||||
|
view = {}
|
||||||
|
view['map'] = opts.delete(:map)
|
||||||
|
if opts[:reduce]
|
||||||
|
view['reduce'] = opts.delete(:reduce)
|
||||||
|
opts[:reduce] = false
|
||||||
|
end
|
||||||
|
@@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 (doc.type == '#{type}' && #{key_protection}) {
|
||||||
|
emit(#{key_emit}, null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
JAVASCRIPT
|
||||||
|
@@design_doc['views'][method_name] = {
|
||||||
|
'map' => map_function
|
||||||
|
}
|
||||||
|
end
|
||||||
|
|
||||||
def fetch_view view_name, opts
|
@@design_doc_fresh = false
|
||||||
retryable = true
|
|
||||||
begin
|
|
||||||
database.view(view_name, opts)
|
|
||||||
# the design doc could have been deleted by a rouge process
|
|
||||||
rescue RestClient::ResourceNotFound => e
|
|
||||||
if retryable
|
|
||||||
refresh_design_doc
|
|
||||||
retryable = false
|
|
||||||
retry
|
|
||||||
else
|
|
||||||
raise e
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def design_doc_id
|
self.meta_class.instance_eval do
|
||||||
"_design/#{self.to_s}"
|
define_method method_name do |*args|
|
||||||
end
|
query = opts.merge(args[0] || {})
|
||||||
|
query[:raw] = true if query[:reduce]
|
||||||
|
unless @@design_doc_fresh
|
||||||
|
refresh_design_doc
|
||||||
|
end
|
||||||
|
raw = query.delete(:raw)
|
||||||
|
view_name = "#{type}/#{method_name}"
|
||||||
|
|
||||||
def default_design_doc
|
view = fetch_view(view_name, query)
|
||||||
{
|
if raw
|
||||||
"_id" => design_doc_id,
|
view
|
||||||
"language" => "javascript",
|
else
|
||||||
"views" => {}
|
# TODO this can be optimized once the include-docs patch is applied
|
||||||
}
|
view['rows'].collect{|r|new(database.get(r['id']))}
|
||||||
end
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
def refresh_design_doc
|
private
|
||||||
saved = database.get(design_doc_id) rescue nil
|
|
||||||
if saved
|
def fetch_view view_name, opts
|
||||||
@@design_doc['views'].each do |name, view|
|
retryable = true
|
||||||
saved['views'][name] = view
|
begin
|
||||||
end
|
database.view(view_name, opts)
|
||||||
database.save(saved)
|
# the design doc could have been deleted by a rouge process
|
||||||
else
|
rescue RestClient::ResourceNotFound => e
|
||||||
database.save(@@design_doc)
|
if retryable
|
||||||
end
|
refresh_design_doc
|
||||||
@@design_doc_fresh = true
|
retryable = false
|
||||||
end
|
retry
|
||||||
|
else
|
||||||
|
raise e
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def design_doc_id
|
||||||
|
"_design/#{self.to_s}"
|
||||||
|
end
|
||||||
|
|
||||||
|
def default_design_doc
|
||||||
|
{
|
||||||
|
"_id" => design_doc_id,
|
||||||
|
"language" => "javascript",
|
||||||
|
"views" => {}
|
||||||
|
}
|
||||||
|
end
|
||||||
|
|
||||||
|
def refresh_design_doc
|
||||||
|
saved = database.get(design_doc_id) rescue nil
|
||||||
|
if saved
|
||||||
|
@@design_doc['views'].each do |name, view|
|
||||||
|
saved['views'][name] = view
|
||||||
|
end
|
||||||
|
database.save(saved)
|
||||||
|
else
|
||||||
|
database.save(@@design_doc)
|
||||||
|
end
|
||||||
|
@@design_doc_fresh = true
|
||||||
|
end
|
||||||
|
|
||||||
end # class << self
|
end # class << self
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
# returns the database used by this model's class
|
# returns the database used by this model's class
|
||||||
def database
|
def database
|
||||||
self.class.database
|
self.class.database
|
||||||
end
|
end
|
||||||
|
|
||||||
# alias for self['_id']
|
# alias for self['_id']
|
||||||
def id
|
def id
|
||||||
self['_id']
|
self['_id']
|
||||||
|
@ -333,12 +337,12 @@ module CouchRest
|
||||||
def rev
|
def rev
|
||||||
self['_rev']
|
self['_rev']
|
||||||
end
|
end
|
||||||
|
|
||||||
# returns true if the document has never been saved
|
# returns true if the document has never been saved
|
||||||
def new_record?
|
def new_record?
|
||||||
!rev
|
!rev
|
||||||
end
|
end
|
||||||
|
|
||||||
# Saves the document to the db using create or update. Also runs the :save
|
# 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
|
# callbacks. Sets the <tt>_id</tt> and <tt>_rev</tt> fields based on
|
||||||
# CouchDB's response.
|
# CouchDB's response.
|
||||||
|
@ -363,21 +367,21 @@ module CouchRest
|
||||||
end
|
end
|
||||||
|
|
||||||
protected
|
protected
|
||||||
|
|
||||||
# Saves a document for the first time, after running the before(:create)
|
# Saves a document for the first time, after running the before(:create)
|
||||||
# callbacks, and applying the unique_id.
|
# callbacks, and applying the unique_id.
|
||||||
def create
|
def create
|
||||||
set_unique_id if respond_to?(:set_unique_id) # hack
|
set_unique_id if respond_to?(:set_unique_id) # hack
|
||||||
save_doc
|
save_doc
|
||||||
end
|
end
|
||||||
|
|
||||||
# Saves the document and runs the :update callbacks.
|
# Saves the document and runs the :update callbacks.
|
||||||
def update
|
def update
|
||||||
save_doc
|
save_doc
|
||||||
end
|
end
|
||||||
|
|
||||||
private
|
private
|
||||||
|
|
||||||
def save_doc
|
def save_doc
|
||||||
result = database.save self
|
result = database.save self
|
||||||
if result['ok']
|
if result['ok']
|
||||||
|
@ -386,13 +390,13 @@ module CouchRest
|
||||||
end
|
end
|
||||||
result['ok']
|
result['ok']
|
||||||
end
|
end
|
||||||
|
|
||||||
def init_doc
|
def init_doc
|
||||||
self['type'] = self.class.to_s
|
self['type'] = self.class.to_s
|
||||||
end
|
end
|
||||||
|
|
||||||
include ::Extlib::Hook
|
include ::Extlib::Hook
|
||||||
register_instance_hooks :save, :create, :update, :destroy
|
register_instance_hooks :save, :create, :update, :destroy
|
||||||
|
|
||||||
end # class Model
|
end # class Model
|
||||||
end # module CouchRest
|
end # module CouchRest
|
Loading…
Add table
Add a link
Reference in a new issue