couchrest_model/lib/couchrest/core/model.rb

614 lines
20 KiB
Ruby
Raw Normal View History

2008-10-03 08:30:41 +02:00
require 'rubygems'
2009-01-20 01:07:14 +01:00
begin
require 'extlib'
rescue
puts "CouchRest::Model requires extlib. This is left out of the gemspec on purpose."
raise
end
2008-10-03 06:21:48 +02:00
require 'digest/md5'
require File.dirname(__FILE__) + '/document'
2009-01-13 05:49:57 +01:00
require 'mime/types'
2009-01-13 22:06:25 +01:00
# = CouchRest::Model - Document modeling, the CouchDB way
2008-09-29 18:55:40 +02:00
module CouchRest
2009-01-13 22:06:25 +01:00
# = CouchRest::Model - Document modeling, the CouchDB way
2008-10-03 23:23:31 +02:00
#
2008-10-02 20:32:11 +02:00
# CouchRest::Model provides an ORM-like interface for CouchDB documents. It
# avoids all usage of <tt>method_missing</tt>, and tries to strike a balance
# between usability and magic. See CouchRest::Model#view_by for
# documentation about the view-generation system.
2008-10-03 23:23:31 +02:00
#
2008-09-30 08:16:44 +02:00
# ==== Example
2008-10-03 23:23:31 +02:00
#
2008-10-02 20:32:11 +02:00
# 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.
2008-10-03 23:23:31 +02:00
#
2008-10-02 19:45:08 +02:00
# class Article < CouchRest::Model
2008-12-14 12:05:02 +01:00
# use_database CouchRest.database!('http://127.0.0.1:5984/couchrest-model-test')
2008-09-30 08:16:44 +02:00
# unique_id :slug
#
# view_by :date, :descending => true
# view_by :user_id, :date
#
# view_by :tags,
# :map =>
# "function(doc) {
2008-10-03 01:39:06 +02:00
# if (doc['couchrest-type'] == 'Article' && doc.tags) {
2008-09-30 08:16:44 +02:00
# doc.tags.forEach(function(tag){
# emit(tag, 1);
# });
# }
# }",
# :reduce =>
# "function(keys, values, rereduce) {
# return sum(values);
# }"
#
# key_writer :date
# key_reader :slug, :created_at, :updated_at
# key_accessor :title, :tags
#
# timestamps!
#
# before(:create, :generate_slug_from_title)
# def generate_slug_from_title
2008-10-02 19:45:08 +02:00
# self['slug'] = title.downcase.gsub(/[^a-z0-9]/,'-').squeeze('-').gsub(/^\-|\-$/,'')
2008-09-30 08:16:44 +02:00
# end
# end
2008-10-03 23:23:31 +02:00
#
# ==== Examples of finding articles with these views:
#
# * All the articles by Barney published in the last 24 hours. Note that we
# use <tt>{}</tt> as a special value that sorts after all strings,
# numbers, and arrays.
#
# Article.by_user_id_and_date :startkey => ["barney", Time.now - 24 * 3600], :endkey => ["barney", {}]
#
# * The most recent 20 articles. Remember that the <tt>view_by :date</tt>
# has the default option <tt>:descending => true</tt>.
#
2009-01-05 06:00:36 +01:00
# Article.by_date :limit => 20
2008-10-03 23:23:31 +02:00
#
# * The raw CouchDB view reduce result for the custom <tt>:tags</tt> view.
# In this case we'll get a count of the number of articles tagged "ruby".
#
# Article.by_tags :key => "ruby", :reduce => true
#
2008-11-04 07:52:50 +01:00
class Model < Document
2008-10-02 19:45:08 +02:00
# instantiates the hash by converting all the keys to strings.
def initialize keys = {}
2008-11-04 07:52:50 +01:00
super(keys)
2008-10-03 01:39:06 +02:00
apply_defaults
2008-10-03 02:13:59 +02:00
cast_keys
2008-10-02 19:45:08 +02:00
unless self['_id'] && self['_rev']
2008-10-03 01:39:06 +02:00
self['couchrest-type'] = self.class.to_s
2008-10-02 19:45:08 +02:00
end
end
2008-10-03 01:27:45 +02:00
2008-10-03 08:30:41 +02:00
# this is the CouchRest::Database that model classes will use unless
# they override it with <tt>use_database</tt>
cattr_accessor :default_database
class_inheritable_accessor :casts
class_inheritable_accessor :default_obj
class_inheritable_accessor :class_database
2008-11-09 01:28:58 +01:00
class_inheritable_accessor :design_doc
2008-10-03 08:30:41 +02:00
class_inheritable_accessor :design_doc_slug_cache
class_inheritable_accessor :design_doc_fresh
2008-10-03 01:27:45 +02:00
2008-10-03 08:30:41 +02:00
class << self
2008-10-02 19:45:08 +02:00
# override the CouchRest::Model-wide default_database
2008-10-03 01:27:45 +02:00
def use_database db
2008-10-03 08:30:41 +02:00
self.class_database = db
2008-10-03 01:27:45 +02:00
end
# returns the CouchRest::Database instance that this class uses
def database
2008-10-03 08:30:41 +02:00
self.class_database || CouchRest::Model.default_database
2008-10-03 01:27:45 +02:00
end
2008-10-03 20:11:06 +02:00
# Load a document from the database by id
2008-10-03 01:27:45 +02:00
def get id
doc = database.get id
new(doc)
end
2008-10-03 20:11:06 +02:00
# Load all documents that have the "couchrest-type" field equal to the
2008-11-04 03:08:14 +01:00
# name of the current class. Take the standard set of
2008-10-03 20:11:06 +02:00
# CouchRest::Database#view options.
def all opts = {}, &block
self.design_doc ||= Design.new(default_design_doc)
unless design_doc_fresh
refresh_design_doc
end
view :all, opts, &block
end
2008-10-03 08:30:41 +02:00
2008-11-04 03:08:14 +01:00
# Load the first document that have the "couchrest-type" field equal to
# the name of the current class.
#
# ==== Returns
# Object:: The first object instance available
# or
# Nil:: if no instances available
#
# ==== Parameters
# opts<Hash>::
# View options, see <tt>CouchRest::Database#view</tt> options for more info.
2008-11-04 01:40:19 +01:00
def first opts = {}
2009-01-05 06:00:36 +01:00
first_instance = self.all(opts.merge!(:limit => 1))
2008-11-04 01:40:19 +01:00
first_instance.empty? ? nil : first_instance.first
end
2008-10-03 02:13:59 +02:00
# Cast a field as another class. The class must be happy to have the
# field's primitive type as the argument to it's constuctur. Classes
2008-10-03 02:13:59 +02:00
# which inherit from CouchRest::Model are happy to act as sub-objects
# for any fields that are stored in JSON as object (and therefore are
# parsed from the JSON as Ruby Hashes).
#
# Example:
#
# class Post < CouchRest::Model
#
# key_accessor :title, :body, :author
#
# cast :author, :as => 'Author'
#
# end
#
# post.author.class #=> Author
#
# Using the same example, if a Post should have many Comments, we
# would declare it like this:
#
# class Post < CouchRest::Model
#
# key_accessor :title, :body, :author, comments
#
# cast :author, :as => 'Author'
# cast :comments, :as => ['Comment']
#
# end
#
# post.author.class #=> Author
# post.comments.class #=> Array
# post.comments.first #=> Comment
#
2008-10-03 01:27:45 +02:00
def cast field, opts = {}
2008-10-03 08:30:41 +02:00
self.casts ||= {}
self.casts[field.to_s] = opts
2008-10-03 02:13:59 +02:00
end
2008-10-03 01:27:45 +02:00
# Defines methods for reading and writing from fields in the document.
# 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
# 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
# corresponding field on the CouchDB document.
def key_reader *keys
keys.each do |method|
key = method.to_s
define_method method do
self[key]
end
end
end
def default
2008-10-03 08:30:41 +02:00
self.default_obj
2008-10-03 01:27:45 +02:00
end
2008-10-03 08:30:41 +02:00
2008-10-03 01:27:45 +02:00
def set_default hash
2008-10-03 08:30:41 +02:00
self.default_obj = hash
2008-10-03 01:27:45 +02:00
end
# 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(:save) do
self['updated_at'] = Time.now
self['created_at'] = self['updated_at'] if new_document?
2008-10-03 01:27:45 +02:00
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 = 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) {
2008-10-03 01:39:06 +02:00
# if (doc['couchrest-type'] == 'Post' && doc.tags) {
2008-10-03 01:27:45 +02:00
# 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) {
2008-10-03 01:39:06 +02:00
# if (doc['couchrest-type'] == 'Post' && doc.date) {
2008-10-03 01:27:45 +02:00
# 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
2008-10-03 21:58:45 +02:00
# <tt>spec/core/model_spec.rb</tt>.
2008-11-09 01:28:58 +01:00
2008-10-03 01:27:45 +02:00
def view_by *keys
2008-11-09 01:28:58 +01:00
self.design_doc ||= Design.new(default_design_doc)
opts = keys.pop if keys.last.is_a?(Hash)
opts ||= {}
ducktype = opts.delete(:ducktype)
2008-11-22 23:29:03 +01:00
unless ducktype || opts[:map]
opts[:guards] ||= []
opts[:guards].push "(doc['couchrest-type'] == '#{self.to_s}')"
end
keys.push opts
2008-11-09 01:28:58 +01:00
self.design_doc.view_by(*keys)
self.design_doc_fresh = false
2008-10-15 00:30:38 +02:00
end
2008-10-03 01:27:45 +02:00
2008-10-15 00:30:38 +02:00
def method_missing m, *args
2008-11-09 01:28:58 +01:00
if has_view?(m)
2008-10-15 00:30:38 +02:00
query = args.shift || {}
2008-11-09 01:28:58 +01:00
view(m, query, *args)
2008-10-15 00:30:38 +02:00
else
super
end
end
2008-10-16 08:26:43 +02:00
# returns stored defaults if the there is a view named this in the design doc
2008-10-15 00:30:38 +02:00
def has_view?(view)
view = view.to_s
design_doc && design_doc['views'] && design_doc['views'][view]
2008-10-03 01:27:45 +02:00
end
2008-10-14 10:07:48 +02:00
# Dispatches to any named view.
def view name, query={}, &block
2008-10-15 00:30:38 +02:00
unless design_doc_fresh
refresh_design_doc
end
query[:raw] = true if query[:reduce]
raw = query.delete(:raw)
2008-11-09 01:28:58 +01:00
fetch_view_with_docs(name, query, raw, &block)
2008-10-14 10:07:48 +02:00
end
2008-11-23 00:40:14 +01:00
def all_design_doc_versions
database.documents :startkey => "_design/#{self.to_s}-",
:endkey => "_design/#{self.to_s}-\u9999"
end
# Deletes any non-current design docs that were created by this class.
# Running this when you're deployed version of your application is steadily
# and consistently using the latest code, is the way to clear out old design
# docs. Running it to early could mean that live code has to regenerate
# potentially large indexes.
def cleanup_design_docs!
ddocs = all_design_doc_versions
ddocs["rows"].each do |row|
if (row['id'] != design_doc_id)
database.delete({
"_id" => row['id'],
"_rev" => row['value']['rev']
})
end
end
end
2008-10-03 01:27:45 +02:00
private
2008-10-14 10:07:48 +02:00
def fetch_view_with_docs name, opts, raw=false, &block
2008-10-03 08:30:41 +02:00
if raw
2008-10-14 10:07:48 +02:00
fetch_view name, opts, &block
2008-10-03 08:30:41 +02:00
else
2008-10-08 21:32:22 +02:00
begin
2008-10-14 10:07:48 +02:00
view = fetch_view name, opts.merge({:include_docs => true}), &block
2008-10-15 00:30:38 +02:00
view['rows'].collect{|r|new(r['doc'])} if view['rows']
2008-10-08 21:32:22 +02:00
rescue
# fallback for old versions of couchdb that don't
# have include_docs support
2008-10-14 10:07:48 +02:00
view = fetch_view name, opts, &block
2008-10-15 00:30:38 +02:00
view['rows'].collect{|r|new(database.get(r['id']))} if view['rows']
2008-10-08 21:32:22 +02:00
end
2008-10-03 08:30:41 +02:00
end
end
2008-10-14 10:07:48 +02:00
def fetch_view view_name, opts, &block
2008-10-03 01:27:45 +02:00
retryable = true
begin
2008-11-09 01:28:58 +01:00
design_doc.view(view_name, opts, &block)
2008-10-03 01:27:45 +02:00
# 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
2008-11-23 00:40:14 +01:00
def design_doc_id
"_design/#{design_doc_slug}"
end
2008-10-03 06:21:48 +02:00
def design_doc_slug
2008-10-03 08:30:41 +02:00
return design_doc_slug_cache if design_doc_slug_cache && design_doc_fresh
2008-10-03 06:21:48 +02:00
funcs = []
2008-11-09 01:28:58 +01:00
design_doc['views'].each do |name, view|
2008-10-03 08:30:41 +02:00
funcs << "#{name}/#{view['map']}#{view['reduce']}"
2008-10-03 06:21:48 +02:00
end
md5 = Digest::MD5.hexdigest(funcs.sort.join(''))
2008-10-03 08:30:41 +02:00
self.design_doc_slug_cache = "#{self.to_s}-#{md5}"
2008-10-03 01:27:45 +02:00
end
def default_design_doc
{
"language" => "javascript",
2008-10-03 08:30:41 +02:00
"views" => {
'all' => {
'map' => "function(doc) {
if (doc['couchrest-type'] == '#{self.to_s}') {
emit(null,null);
}
}"
}
}
2008-10-03 01:27:45 +02:00
}
end
def refresh_design_doc
2008-11-23 00:40:14 +01:00
did = design_doc_id
saved = database.get(did) rescue nil
if saved
design_doc['views'].each do |name, view|
saved['views'][name] = view
end
database.save(saved)
2009-01-19 23:49:48 +01:00
self.design_doc = saved
else
design_doc['_id'] = did
design_doc.delete('_rev')
design_doc.database = database
design_doc.save
end
self.design_doc_fresh = true
end
2008-10-02 19:45:08 +02:00
end # class << self
# returns the database used by this model's class
def database
self.class.database
end
2008-10-03 01:27:45 +02:00
2008-10-03 21:58:45 +02:00
# Takes a hash as argument, and applies the values by using writer methods
# for each key. It doesn't save the document at the end. Raises a NoMethodError if the corresponding methods are
# missing. In case of error, no attributes are changed.
def update_attributes_without_saving hash
2008-10-03 21:58:45 +02:00
hash.each do |k, v|
raise NoMethodError, "#{k}= method not available, use key_accessor or key_writer :#{k}" unless self.respond_to?("#{k}=")
2008-10-03 21:58:45 +02:00
end
hash.each do |k, v|
self.send("#{k}=",v)
end
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.
def update_attributes hash
update_attributes_without_saving hash
2008-10-03 21:58:45 +02:00
save
end
# for compatibility with old-school frameworks
alias :new_record? :new_document?
# Overridden to set the unique ID.
def save bulk = false
2009-01-13 06:06:26 +01:00
set_unique_id if new_document? && self.respond_to?(:set_unique_id)
super(bulk)
end
# Saves the document to the db using create or update. Raises an exception
# if the document is not saved properly.
def save!
raise "#{self.inspect} failed to save" unless self.save
end
# Deletes the document from the database. Runs the :destroy callbacks.
2008-10-02 20:32:11 +02:00
# Removes the <tt>_id</tt> and <tt>_rev</tt> fields, preparing the
# document to be saved to a new <tt>_id</tt>.
2008-10-02 20:06:37 +02:00
def destroy
result = database.delete self
if result['ok']
self['_rev'] = nil
self['_id'] = nil
end
result['ok']
end
2009-01-13 05:49:57 +01:00
# creates a file attachment to the current doc
def create_attachment(args={})
raise ArgumentError unless args[:file] && args[:name]
return if has_attachment?(args[:name])
2009-01-13 05:49:57 +01:00
self['_attachments'] ||= {}
set_attachment_attr(args)
rescue ArgumentError => e
raise ArgumentError, 'You must specify :file and :name'
2009-01-13 05:49:57 +01:00
end
# reads the data from an attachment
def read_attachment(attachment_name)
Base64.decode64(database.fetch_attachment(self.id, attachment_name))
end
# modifies a file attachment on the current doc
def update_attachment(args={})
raise ArgumentError unless args[:file] && args[:name]
return unless has_attachment?(args[:name])
delete_attachment(args[:name])
set_attachment_attr(args)
rescue ArgumentError => e
raise ArgumentError, 'You must specify :file and :name'
2009-01-13 05:49:57 +01:00
end
# deletes a file attachment from the current doc
def delete_attachment(attachment_name)
return unless self['_attachments']
self['_attachments'].delete attachment_name
end
2008-10-30 04:56:10 +01:00
# returns true if attachment_name exists
2008-10-30 04:56:10 +01:00
def has_attachment?(attachment_name)
!!(self['_attachments'] && self['_attachments'][attachment_name] && !self['_attachments'][attachment_name].empty?)
end
2009-01-13 05:49:57 +01:00
# returns URL to fetch the attachment from
def attachment_url(attachment_name)
return unless has_attachment?(attachment_name)
"#{database.root}/#{self.id}/#{attachment_name}"
end
2008-10-02 19:45:08 +02:00
private
2008-10-03 01:27:45 +02:00
2008-10-03 01:39:06 +02:00
def apply_defaults
return unless new_document?
2008-10-03 01:39:06 +02:00
if self.class.default
self.class.default.each do |k,v|
2009-01-13 22:06:25 +01:00
unless self.key?(k.to_s)
if v.class == Proc
self[k.to_s] = v.call
else
self[k.to_s] = Marshal.load(Marshal.dump(v))
end
end
2008-10-03 01:39:06 +02:00
end
end
2008-10-02 19:45:08 +02:00
end
2008-10-03 01:27:45 +02:00
2008-10-03 02:13:59 +02:00
def cast_keys
return unless self.class.casts
2008-10-03 06:21:48 +02:00
# TODO move the argument checking to the cast method for early crashes
2008-10-03 02:13:59 +02:00
self.class.casts.each do |k,v|
next unless self[k]
target = v[:as]
2009-01-01 01:00:24 +01:00
v[:send] || 'new'
2008-10-03 08:56:22 +02:00
if target.is_a?(Array)
klass = ::Extlib::Inflection.constantize(target[0])
2008-10-03 02:13:59 +02:00
self[k] = self[k].collect do |value|
2009-01-01 01:00:24 +01:00
(!v[:send] && klass == Time) ? Time.parse(value) : klass.send((v[:send] || 'new'), value)
2008-10-03 02:13:59 +02:00
end
else
2009-01-01 01:00:24 +01:00
self[k] = if (!v[:send] && target == 'Time')
Time.parse(self[k])
else
::Extlib::Inflection.constantize(target).send((v[:send] || 'new'), self[k])
end
2008-10-03 02:13:59 +02:00
end
end
end
2009-01-13 05:49:57 +01:00
def encode_attachment(data)
Base64.encode64(data).gsub(/\r|\n/,'')
end
def get_mime_type(file)
MIME::Types.type_for(file.path).empty? ?
2008-10-22 07:41:21 +02:00
'text\/plain' : MIME::Types.type_for(file.path).first.content_type.gsub(/\//,'\/')
2009-01-13 05:49:57 +01:00
end
def set_attachment_attr(args)
content_type = args[:content_type] ? args[:content_type] : get_mime_type(args[:file])
self['_attachments'][args[:name]] = {
'content-type' => content_type,
'data' => encode_attachment(args[:file].read)
2009-01-13 05:49:57 +01:00
}
end
2008-10-02 19:45:08 +02:00
include ::Extlib::Hook
register_instance_hooks :save, :destroy
2008-10-03 01:27:45 +02:00
2008-10-02 19:45:08 +02:00
end # class Model
end # module CouchRest