fix indentation

This commit is contained in:
Chris Anderson 2008-10-02 16:27:45 -07:00
parent 8ac6b78170
commit 8cfed5af4f

View file

@ -70,250 +70,254 @@ module CouchRest
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
key_writer *keys
key_reader *keys
end
# For each argument key, define a method <tt>key=</tt> that sets the end
# corresponding field on the CouchDB document.
def key_writer *keys
keys.each do |method|
key = method.to_s
define_method "#{method}=" do |value|
self[key] = value
end
end
end
# For each argument key, define a method <tt>key</tt> that reads 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_reader *keys def key_accessor *keys
keys.each do |method| key_writer *keys
key = method.to_s key_reader *keys
define_method method do end
self[key]
end
end
end
def default # For each argument key, define a method <tt>key=</tt> that sets the
@default # corresponding field on the CouchDB document.
end def key_writer *keys
keys.each do |method|
key = method.to_s
define_method "#{method}=" do |value|
self[key] = value
end
end
end
def set_default hash # For each argument key, define a method <tt>key</tt> that reads the
@default = hash # corresponding field on the CouchDB document.
end def key_reader *keys
keys.each do |method|
key = method.to_s
define_method method do
self[key]
end
end
end
# Automatically set <tt>updated_at</tt> and <tt>created_at</tt> fields def default
# on the document whenever saving occurs. CouchRest uses a pretty @default
# decent time format by default. See Time#to_json end
def timestamps!
before(:create) do
self['updated_at'] = self['created_at'] = Time.now
end
before(:update) do
self['updated_at'] = Time.now
end
end
# Name a method that will be called before the document is first saved, def set_default hash
# which returns a string to be used for the document's <tt>_id</tt>. @default = hash
# 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 # Automatically set <tt>updated_at</tt> and <tt>created_at</tt> fields
# of <tt>by</tt> and the keys joined by <tt>_and_</tt> # on the document whenever saving occurs. CouchRest uses a pretty
# # decent time format by default. See Time#to_json
# ==== Example views: def timestamps!
# before(:create) do
# class Post self['updated_at'] = self['created_at'] = Time.now
# # view with default options end
# # query with Post.by_date before(:update) do
# view_by :date, :descending => true self['updated_at'] = Time.now
# end
# # view with compound sort-keys end
# # 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_')}" # Name a method that will be called before the document is first saved,
@@design_doc ||= default_design_doc # 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
if opts[:map] # Define a CouchDB view. The name of the view will be the concatenation
view = {} # of <tt>by</tt> and the keys joined by <tt>_and_</tt>
view['map'] = opts.delete(:map) #
if opts[:reduce] # ==== Example views:
view['reduce'] = opts.delete(:reduce) #
opts[:reduce] = false # class Post
end # # view with default options
@@design_doc['views'][method_name] = view # # query with Post.by_date
else # view_by :date, :descending => true
doc_keys = keys.collect{|k|"doc['#{k}']"} #
key_protection = doc_keys.join(' && ') # # view with compound sort-keys
key_emit = doc_keys.length == 1 ? "#{doc_keys.first}" : "[#{doc_keys.join(', ')}]" # # query with Post.by_user_id_and_date
map_function = <<-JAVASCRIPT # view_by :user_id, :date
function(doc) { #
if (doc.type == '#{type}' && #{key_protection}) { # # view with custom map/reduce functions
emit(#{key_emit}, null); # # query with Post.by_tags :reduce => true
} # view_by :tags,
} # :map =>
JAVASCRIPT # "function(doc) {
@@design_doc['views'][method_name] = { # if (doc.type == 'Post' && doc.tags) {
'map' => map_function # doc.tags.forEach(function(tag){
} # emit(doc.tag, 1);
end # });
# }
# }",
# :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
@@design_doc_fresh = false method_name = "by_#{keys.join('_and_')}"
@@design_doc ||= default_design_doc
self.meta_class.instance_eval do if opts[:map]
define_method method_name do |*args| view = {}
query = opts.merge(args[0] || {}) view['map'] = opts.delete(:map)
query[:raw] = true if query[:reduce] if opts[:reduce]
unless @@design_doc_fresh view['reduce'] = opts.delete(:reduce)
refresh_design_doc opts[:reduce] = false
end end
raw = query.delete(:raw) @@design_doc['views'][method_name] = view
view_name = "#{type}/#{method_name}" 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
view = fetch_view(view_name, query) @@design_doc_fresh = false
if raw
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 self.meta_class.instance_eval do
define_method method_name do |*args|
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 fetch_view view_name, opts view = fetch_view(view_name, query)
retryable = true if raw
begin view
database.view(view_name, opts) else
# the design doc could have been deleted by a rouge process # TODO this can be optimized once the include-docs patch is applied
rescue RestClient::ResourceNotFound => e view['rows'].collect{|r|new(database.get(r['id']))}
if retryable end
refresh_design_doc end
retryable = false end
retry end
else
raise e
end
end
end
def design_doc_id private
"_design/#{self.to_s}"
end
def default_design_doc def fetch_view view_name, opts
{ retryable = true
"_id" => design_doc_id, begin
"language" => "javascript", database.view(view_name, opts)
"views" => {} # the design doc could have been deleted by a rouge process
} rescue RestClient::ResourceNotFound => e
end if retryable
refresh_design_doc
retryable = false
retry
else
raise e
end
end
end
def refresh_design_doc def design_doc_id
saved = database.get(design_doc_id) rescue nil "_design/#{self.to_s}"
if saved end
@@design_doc['views'].each do |name, view|
saved['views'][name] = view def default_design_doc
end {
database.save(saved) "_id" => design_doc_id,
else "language" => "javascript",
database.save(@@design_doc) "views" => {}
end }
@@design_doc_fresh = true end
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