Merged
This commit is contained in:
parent
b7593006c8
commit
2b0694e1e2
15 changed files with 422 additions and 435 deletions
164
README.md
164
README.md
|
@ -28,6 +28,170 @@ Note: CouchRest::ExtendedDocument only supports CouchDB 0.10.0 or newer.
|
||||||
|
|
||||||
end
|
end
|
||||||
|
|
||||||
|
@cat = Cat.new(:name => 'Felix', :nicknames => ['so cute', 'sweet kitty'])
|
||||||
|
|
||||||
|
@cat.new? # true
|
||||||
|
@cat.save
|
||||||
|
|
||||||
|
@cat['name'] # "Felix"
|
||||||
|
|
||||||
|
@cat.nicknames << 'getoffdamntable'
|
||||||
|
|
||||||
|
@cat = Cat.new
|
||||||
|
@cat.update_attributes(:name => 'Felix', :random_text => 'feline')
|
||||||
|
@cat.new? # false
|
||||||
|
@cat.random_text # Raises error!
|
||||||
|
|
||||||
|
|
||||||
|
### Properties
|
||||||
|
|
||||||
|
Only attributes with a property definition will be stored be ExtendedDocument (as opposed
|
||||||
|
to a normal CouchRest Document which will store everything). To help prevent confusion,
|
||||||
|
a property should be considered as the definition of an attribute. An attribute must be associated
|
||||||
|
with a property, but a property may not have any attributes associated if none have been set.
|
||||||
|
|
||||||
|
|
||||||
|
In its simplest form, a property
|
||||||
|
will only create a getter and setter passing all attribute data directly to the database. Assuming the attribute
|
||||||
|
provided responds to +to_json+, there will not be any problems saving it, but when loading the
|
||||||
|
data back it will either be a string, number, array, or hash:
|
||||||
|
|
||||||
|
class Cat < CouchRest::ExtendedDocument
|
||||||
|
property :name
|
||||||
|
property :birthday
|
||||||
|
end
|
||||||
|
|
||||||
|
@cat = Cat.new(:name => 'Felix', :birthday => 2.years.ago)
|
||||||
|
@cat.name # 'Felix'
|
||||||
|
@cat.birthday.is_a?(Time) # True!
|
||||||
|
@cat.save
|
||||||
|
@cat = Cat.find(@cat.id)
|
||||||
|
@cat.name # 'Felix'
|
||||||
|
@cat.birthday.is_a?(Time) # False!
|
||||||
|
|
||||||
|
Properties create getters and setters similar to the following:
|
||||||
|
|
||||||
|
def name
|
||||||
|
read_attribute('name')
|
||||||
|
end
|
||||||
|
|
||||||
|
def name=(value)
|
||||||
|
write_attribute('name', value)
|
||||||
|
end
|
||||||
|
|
||||||
|
Properties can also have a type which
|
||||||
|
will be used for casting data retrieved from CouchDB when the attribute is set:
|
||||||
|
|
||||||
|
class Cat < CouchRest::ExtendedDocument
|
||||||
|
property :name, String
|
||||||
|
property :last_fed_at, Time
|
||||||
|
end
|
||||||
|
|
||||||
|
@cat = Cat.new(:name => 'Felix', :last_fed_at => 10.minutes.ago)
|
||||||
|
@cat.last_fed_at.is_a?(Time) # True!
|
||||||
|
@cat.save
|
||||||
|
@cat = Cat.find(@cat.id)
|
||||||
|
@cat.last_fed_at < 20.minutes.ago # True!
|
||||||
|
|
||||||
|
|
||||||
|
Booleans or TrueClass will also create a getter with question mark at the end:
|
||||||
|
|
||||||
|
class Cat < CouchRest::ExtendedDocument
|
||||||
|
property :awake, TrueClass, :default => true
|
||||||
|
end
|
||||||
|
|
||||||
|
@cat.awake? # true
|
||||||
|
|
||||||
|
Adding the +:default+ option will ensure the attribute always has a value.
|
||||||
|
|
||||||
|
Defining a property as read-only will mean that its value is set only when read from the
|
||||||
|
database and that it will not have a setter method. You can however update a read-only
|
||||||
|
attribute using the +write_attribute+ method:
|
||||||
|
|
||||||
|
class Cat < CouchRest::ExtendedDocument
|
||||||
|
property :name, String
|
||||||
|
property :lives, Integer, :default => 9, :readonly => true
|
||||||
|
|
||||||
|
def fall_off_balcony!
|
||||||
|
write_attribute(:lives, lives - 1)
|
||||||
|
save
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
@cat = Cat.new(:name => "Felix")
|
||||||
|
@cat.fall_off_balcony!
|
||||||
|
@cat.lives # Now 8!
|
||||||
|
|
||||||
|
|
||||||
|
### Property Arrays
|
||||||
|
|
||||||
|
An attribute may also contain an array of data. ExtendedDocument handles this, along
|
||||||
|
with casting, by defining the class of the child attributes inside an Array:
|
||||||
|
|
||||||
|
class Cat < CouchRest::ExtendedDocument
|
||||||
|
property :name, String
|
||||||
|
property :nicknames, [String]
|
||||||
|
end
|
||||||
|
|
||||||
|
By default, the array will be ready to use from the moment the object as been instantiated:
|
||||||
|
|
||||||
|
@cat = Cat.new(:name => 'Fluffy')
|
||||||
|
@cat.nicknames << 'Buffy'
|
||||||
|
|
||||||
|
@cat.nicknames == ['Buffy']
|
||||||
|
|
||||||
|
When anything other than a string is set as the class of a property, the array will be converted
|
||||||
|
into special wrapper called a CastedArray. If the child objects respond to the 'casted_by' method
|
||||||
|
(such as those created with CastedModel, below) it will contain a reference to the parent.
|
||||||
|
|
||||||
|
### Casted Models
|
||||||
|
|
||||||
|
ExtendedDocument allows you to take full advantage of CouchDB's ability to store complex
|
||||||
|
documents and retrieve them using the CastedModel module. Simply include the module in
|
||||||
|
a Hash (or other model that responds to the [] and []= methods) and set any properties
|
||||||
|
you'd like to use. For example:
|
||||||
|
|
||||||
|
class CatToy << Hash
|
||||||
|
include CouchRest::CastedModel
|
||||||
|
|
||||||
|
property :name, String
|
||||||
|
property :purchased, Date
|
||||||
|
end
|
||||||
|
|
||||||
|
class Cat << CouchRest::ExtendedDocument
|
||||||
|
property :name, String
|
||||||
|
property :toys, [CatToy]
|
||||||
|
end
|
||||||
|
|
||||||
|
@cat = Cat.new(:name => 'Felix', :toys => [{:name => 'mouse', :purchases => 1.month.ago}])
|
||||||
|
@cat.toys.first.class == CatToy
|
||||||
|
@cat.toys.first.name == 'mouse'
|
||||||
|
|
||||||
|
Additionally, any hashes sent to the property will automatically be converted:
|
||||||
|
|
||||||
|
@cat.toys << {:name => 'catnip ball'}
|
||||||
|
@cat.toys.last.is_a?(CatToy) # True!
|
||||||
|
|
||||||
|
Of course, to use your own classes they *must* be defined before the parent uses them otherwise
|
||||||
|
Ruby will bring up a missing constant error. To avoid this, or if you have a really simple array of data
|
||||||
|
you'd like to model, the latest version of ExtendedDocument (> 1.0.0) supports creating
|
||||||
|
anonymous classes:
|
||||||
|
|
||||||
|
class Cat << CouchRest::ExtendedDocument
|
||||||
|
property :name, String
|
||||||
|
|
||||||
|
property :toys do |toy|
|
||||||
|
toy.property :name, String
|
||||||
|
toy.property :rating, Integer
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
@cat = Cat.new(:name => 'Felix', :toys => [{:name => 'mouse', :rating => 3}, {:name => 'catnip ball', :rating => 5}])
|
||||||
|
@cat.toys.last.rating == 5
|
||||||
|
@cat.toys.last.name == 'catnip ball'
|
||||||
|
|
||||||
|
Using this method of anonymous classes will *only* create arrays of objects.
|
||||||
|
|
||||||
### Notable Issues
|
### Notable Issues
|
||||||
|
|
||||||
ExtendedDocument uses active_support for some of its internals. Ensure you have a stable active support gem installed
|
ExtendedDocument uses active_support for some of its internals. Ensure you have a stable active support gem installed
|
||||||
|
|
|
@ -6,20 +6,34 @@
|
||||||
module CouchRest
|
module CouchRest
|
||||||
class CastedArray < Array
|
class CastedArray < Array
|
||||||
attr_accessor :casted_by
|
attr_accessor :casted_by
|
||||||
|
attr_accessor :property
|
||||||
|
|
||||||
|
def initialize(array, property)
|
||||||
|
self.property = property
|
||||||
|
super(array)
|
||||||
|
end
|
||||||
|
|
||||||
def << obj
|
def << obj
|
||||||
obj.casted_by = self.casted_by if obj.respond_to?(:casted_by)
|
super(instantiate_and_cast(obj))
|
||||||
super(obj)
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def push(obj)
|
def push(obj)
|
||||||
obj.casted_by = self.casted_by if obj.respond_to?(:casted_by)
|
super(instantiate_and_cast(obj))
|
||||||
super(obj)
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def []= index, obj
|
def []= index, obj
|
||||||
obj.casted_by = self.casted_by if obj.respond_to?(:casted_by)
|
super(index, instantiate_and_cast(obj))
|
||||||
super(index, obj)
|
end
|
||||||
|
|
||||||
|
protected
|
||||||
|
|
||||||
|
def instantiate_and_cast(obj)
|
||||||
|
if self.casted_by && self.property && obj.class != self.property.type_class
|
||||||
|
self.property.cast_value(self.casted_by, obj)
|
||||||
|
else
|
||||||
|
obj.casted_by = self.casted_by if obj.respond_to?(:casted_by)
|
||||||
|
obj
|
||||||
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
|
@ -5,17 +5,15 @@ module CouchRest
|
||||||
base.send(:include, ::CouchRest::Mixins::Callbacks)
|
base.send(:include, ::CouchRest::Mixins::Callbacks)
|
||||||
base.send(:include, ::CouchRest::Mixins::Properties)
|
base.send(:include, ::CouchRest::Mixins::Properties)
|
||||||
base.send(:attr_accessor, :casted_by)
|
base.send(:attr_accessor, :casted_by)
|
||||||
base.send(:attr_accessor, :document_saved)
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def initialize(keys={})
|
def initialize(keys={})
|
||||||
raise StandardError unless self.is_a? Hash
|
raise StandardError unless self.is_a? Hash
|
||||||
apply_defaults # defined in CouchRest::Mixins::Properties
|
apply_all_property_defaults # defined in CouchRest::Mixins::Properties
|
||||||
super()
|
super()
|
||||||
keys.each do |k,v|
|
keys.each do |k,v|
|
||||||
self[k.to_s] = v
|
write_attribute(k.to_s, v)
|
||||||
end if keys
|
end if keys
|
||||||
cast_keys # defined in CouchRest::Mixins::Properties
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def []= key, value
|
def []= key, value
|
||||||
|
@ -36,7 +34,7 @@ module CouchRest
|
||||||
# False if the casted model has already
|
# False if the casted model has already
|
||||||
# been saved in the containing document
|
# been saved in the containing document
|
||||||
def new?
|
def new?
|
||||||
!@document_saved
|
@casted_by.nil? ? true : @casted_by.new?
|
||||||
end
|
end
|
||||||
alias :new_record? :new?
|
alias :new_record? :new?
|
||||||
|
|
||||||
|
|
|
@ -18,6 +18,7 @@ module CouchRest
|
||||||
include CouchRest::Mixins::ClassProxy
|
include CouchRest::Mixins::ClassProxy
|
||||||
include CouchRest::Mixins::Collection
|
include CouchRest::Mixins::Collection
|
||||||
include CouchRest::Mixins::AttributeProtection
|
include CouchRest::Mixins::AttributeProtection
|
||||||
|
include CouchRest::Mixins::Attributes
|
||||||
|
|
||||||
# Including validation here does not work due to the way inheritance is handled.
|
# Including validation here does not work due to the way inheritance is handled.
|
||||||
#include CouchRest::Validation
|
#include CouchRest::Validation
|
||||||
|
@ -57,12 +58,17 @@ module CouchRest
|
||||||
base.new(doc, :directly_set_attributes => true)
|
base.new(doc, :directly_set_attributes => true)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|
||||||
|
# Instantiate a new ExtendedDocument by preparing all properties
|
||||||
|
# using the provided document hash.
|
||||||
|
#
|
||||||
|
# Options supported:
|
||||||
|
#
|
||||||
|
# * :directly_set_attributes: true when data comes directly from database
|
||||||
|
#
|
||||||
def initialize(doc = {}, options = {})
|
def initialize(doc = {}, options = {})
|
||||||
apply_defaults # defined in CouchRest::Mixins::Properties
|
prepare_all_attributes(doc, options) # defined in CouchRest::Mixins::Attributes
|
||||||
remove_protected_attributes(doc) unless options[:directly_set_attributes]
|
|
||||||
directly_set_attributes(doc) unless doc.nil?
|
|
||||||
super(doc)
|
super(doc)
|
||||||
cast_keys # defined in CouchRest::Mixins::Properties
|
|
||||||
unless self['_id'] && self['_rev']
|
unless self['_id'] && self['_rev']
|
||||||
self['couchrest-type'] = self.class.to_s
|
self['couchrest-type'] = self.class.to_s
|
||||||
end
|
end
|
||||||
|
@ -94,12 +100,12 @@ module CouchRest
|
||||||
# decent time format by default. See Time#to_json
|
# decent time format by default. See Time#to_json
|
||||||
def self.timestamps!
|
def self.timestamps!
|
||||||
class_eval <<-EOS, __FILE__, __LINE__
|
class_eval <<-EOS, __FILE__, __LINE__
|
||||||
property(:updated_at, :read_only => true, :type => 'Time', :auto_validation => false)
|
property(:updated_at, Time, :read_only => true, :protected => true, :auto_validation => false)
|
||||||
property(:created_at, :read_only => true, :type => 'Time', :auto_validation => false)
|
property(:created_at, Time, :read_only => true, :protected => true, :auto_validation => false)
|
||||||
|
|
||||||
set_callback :save, :before do |object|
|
set_callback :save, :before do |object|
|
||||||
object['updated_at'] = Time.now
|
write_attribute('updated_at', Time.now)
|
||||||
object['created_at'] = object['updated_at'] if object.new?
|
write_attribute('created_at', Time.now) if object.new?
|
||||||
end
|
end
|
||||||
EOS
|
EOS
|
||||||
end
|
end
|
||||||
|
@ -142,14 +148,6 @@ module CouchRest
|
||||||
|
|
||||||
### instance methods
|
### instance methods
|
||||||
|
|
||||||
# Returns the Class properties
|
|
||||||
#
|
|
||||||
# ==== Returns
|
|
||||||
# Array:: the list of properties for the instance
|
|
||||||
def properties
|
|
||||||
self.class.properties
|
|
||||||
end
|
|
||||||
|
|
||||||
# Gets a reference to the actual document in the DB
|
# Gets a reference to the actual document in the DB
|
||||||
# Calls up to the next document if there is one,
|
# Calls up to the next document if there is one,
|
||||||
# Otherwise we're at the top and we return self
|
# Otherwise we're at the top and we return self
|
||||||
|
@ -163,28 +161,6 @@ module CouchRest
|
||||||
!@casted_by
|
!@casted_by
|
||||||
end
|
end
|
||||||
|
|
||||||
# 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)
|
|
||||||
# remove attributes that cannot be updated, silently ignoring them
|
|
||||||
# which matches Rails behavior when, for instance, setting created_at.
|
|
||||||
# make a copy, we don't want to change arguments
|
|
||||||
attrs = hash.dup
|
|
||||||
%w[_id _rev created_at updated_at].each {|attr| attrs.delete(attr)}
|
|
||||||
check_properties_exist(attrs)
|
|
||||||
set_attributes(attrs)
|
|
||||||
end
|
|
||||||
alias :attributes= :update_attributes_without_saving
|
|
||||||
|
|
||||||
# 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
|
|
||||||
save
|
|
||||||
end
|
|
||||||
|
|
||||||
# for compatibility with old-school frameworks
|
# for compatibility with old-school frameworks
|
||||||
alias :new_record? :new?
|
alias :new_record? :new?
|
||||||
alias :new_document? :new?
|
alias :new_document? :new?
|
||||||
|
@ -255,7 +231,6 @@ module CouchRest
|
||||||
raise ArgumentError, "a document requires a database to be saved to (The document or the #{self.class} default database were not set)" unless database
|
raise ArgumentError, "a document requires a database to be saved to (The document or the #{self.class} default database were not set)" unless database
|
||||||
set_unique_id if new? && self.respond_to?(:set_unique_id)
|
set_unique_id if new? && self.respond_to?(:set_unique_id)
|
||||||
result = database.save_doc(self, bulk)
|
result = database.save_doc(self, bulk)
|
||||||
mark_as_saved
|
|
||||||
result["ok"] == true
|
result["ok"] == true
|
||||||
end
|
end
|
||||||
|
|
||||||
|
@ -281,43 +256,6 @@ module CouchRest
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
protected
|
|
||||||
|
|
||||||
# Set document_saved flag on all casted models to true
|
|
||||||
def mark_as_saved
|
|
||||||
self.each do |key, prop|
|
|
||||||
if prop.is_a?(Array)
|
|
||||||
prop.each do |item|
|
|
||||||
if item.respond_to?(:document_saved)
|
|
||||||
item.send(:document_saved=, true)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
elsif prop.respond_to?(:document_saved)
|
|
||||||
prop.send(:document_saved=, true)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
private
|
|
||||||
|
|
||||||
def check_properties_exist(attrs)
|
|
||||||
attrs.each do |attribute_name, attribute_value|
|
|
||||||
raise NoMethodError, "#{attribute_name}= method not available, use property :#{attribute_name}" unless self.respond_to?("#{attribute_name}=")
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def directly_set_attributes(hash)
|
|
||||||
hash.each do |attribute_name, attribute_value|
|
|
||||||
if self.respond_to?("#{attribute_name}=")
|
|
||||||
self.send("#{attribute_name}=", hash.delete(attribute_name))
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def set_attributes(hash)
|
|
||||||
attrs = remove_protected_attributes(hash)
|
|
||||||
directly_set_attributes(attrs)
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
|
@ -9,3 +9,4 @@ require File.join(mixins_dir, 'extended_attachments')
|
||||||
require File.join(mixins_dir, 'class_proxy')
|
require File.join(mixins_dir, 'class_proxy')
|
||||||
require File.join(mixins_dir, 'collection')
|
require File.join(mixins_dir, 'collection')
|
||||||
require File.join(mixins_dir, 'attribute_protection')
|
require File.join(mixins_dir, 'attribute_protection')
|
||||||
|
require File.join(mixins_dir, 'attributes')
|
||||||
|
|
75
lib/couchrest/mixins/attributes.rb
Normal file
75
lib/couchrest/mixins/attributes.rb
Normal file
|
@ -0,0 +1,75 @@
|
||||||
|
module CouchRest
|
||||||
|
module Mixins
|
||||||
|
module Attributes
|
||||||
|
|
||||||
|
## Support for handling attributes
|
||||||
|
#
|
||||||
|
# This would be better in the properties file, but due to scoping issues
|
||||||
|
# this is not yet possible.
|
||||||
|
#
|
||||||
|
|
||||||
|
def prepare_all_attributes(doc = {}, options = {})
|
||||||
|
apply_all_property_defaults
|
||||||
|
if options[:directly_set_attributes]
|
||||||
|
directly_set_read_only_attributes(doc)
|
||||||
|
else
|
||||||
|
remove_protected_attributes(doc)
|
||||||
|
end
|
||||||
|
directly_set_attributes(doc) unless doc.nil?
|
||||||
|
end
|
||||||
|
|
||||||
|
# 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)
|
||||||
|
# Remove any protected and update all the rest. Any attributes
|
||||||
|
# which do not have a property will simply be ignored.
|
||||||
|
attrs = remove_protected_attributes(hash)
|
||||||
|
directly_set_attributes(attrs)
|
||||||
|
end
|
||||||
|
alias :attributes= :update_attributes_without_saving
|
||||||
|
|
||||||
|
# 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
|
||||||
|
save
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def directly_set_attributes(hash)
|
||||||
|
hash.each do |attribute_name, attribute_value|
|
||||||
|
if self.respond_to?("#{attribute_name}=")
|
||||||
|
self.send("#{attribute_name}=", hash.delete(attribute_name))
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def directly_set_read_only_attributes(hash)
|
||||||
|
property_list = self.properties.map{|p| p.name}
|
||||||
|
hash.each do |attribute_name, attribute_value|
|
||||||
|
next if self.respond_to?("#{attribute_name}=")
|
||||||
|
if property_list.include?(attribute_name)
|
||||||
|
write_attribute(attribute_name, hash.delete(attribute_name))
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def set_attributes(hash)
|
||||||
|
attrs = remove_protected_attributes(hash)
|
||||||
|
directly_set_attributes(attrs)
|
||||||
|
end
|
||||||
|
|
||||||
|
def check_properties_exist(attrs)
|
||||||
|
property_list = self.properties.map{|p| p.name}
|
||||||
|
attrs.each do |attribute_name, attribute_value|
|
||||||
|
raise NoMethodError, "Property #{attribute_name} not created" unless respond_to?("#{attribute_name}=") or property_list.include?(attribute_name)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
|
@ -1,7 +1,6 @@
|
||||||
require 'time'
|
require 'time'
|
||||||
require File.join(File.dirname(__FILE__), '..', 'property')
|
require File.join(File.dirname(__FILE__), '..', 'property')
|
||||||
require File.join(File.dirname(__FILE__), '..', 'casted_array')
|
require File.join(File.dirname(__FILE__), '..', 'casted_array')
|
||||||
require File.join(File.dirname(__FILE__), '..', 'typecast')
|
|
||||||
|
|
||||||
module CouchRest
|
module CouchRest
|
||||||
module Mixins
|
module Mixins
|
||||||
|
@ -9,8 +8,6 @@ module CouchRest
|
||||||
|
|
||||||
class IncludeError < StandardError; end
|
class IncludeError < StandardError; end
|
||||||
|
|
||||||
include ::CouchRest::More::Typecast
|
|
||||||
|
|
||||||
def self.included(base)
|
def self.included(base)
|
||||||
base.class_eval <<-EOS, __FILE__, __LINE__ + 1
|
base.class_eval <<-EOS, __FILE__, __LINE__ + 1
|
||||||
extlib_inheritable_accessor(:properties) unless self.respond_to?(:properties)
|
extlib_inheritable_accessor(:properties) unless self.respond_to?(:properties)
|
||||||
|
@ -19,70 +16,36 @@ module CouchRest
|
||||||
base.extend(ClassMethods)
|
base.extend(ClassMethods)
|
||||||
raise CouchRest::Mixins::Properties::IncludeError, "You can only mixin Properties in a class responding to [] and []=, if you tried to mixin CastedModel, make sure your class inherits from Hash or responds to the proper methods" unless (base.new.respond_to?(:[]) && base.new.respond_to?(:[]=))
|
raise CouchRest::Mixins::Properties::IncludeError, "You can only mixin Properties in a class responding to [] and []=, if you tried to mixin CastedModel, make sure your class inherits from Hash or responds to the proper methods" unless (base.new.respond_to?(:[]) && base.new.respond_to?(:[]=))
|
||||||
end
|
end
|
||||||
|
|
||||||
def apply_defaults
|
# Returns the Class properties
|
||||||
|
#
|
||||||
|
# ==== Returns
|
||||||
|
# Array:: the list of properties for model's class
|
||||||
|
def properties
|
||||||
|
self.class.properties
|
||||||
|
end
|
||||||
|
|
||||||
|
def read_attribute(property)
|
||||||
|
self[property.to_s]
|
||||||
|
end
|
||||||
|
|
||||||
|
def write_attribute(property, value)
|
||||||
|
prop = property.is_a?(::CouchRest::Property) ? property : self.class.properties.detect {|p| p.to_s == property.to_s}
|
||||||
|
raise "Missing property definition for #{property.to_s}" unless prop
|
||||||
|
self[prop.to_s] = prop.cast(self, value)
|
||||||
|
end
|
||||||
|
|
||||||
|
def apply_all_property_defaults
|
||||||
return if self.respond_to?(:new?) && (new? == false)
|
return if self.respond_to?(:new?) && (new? == false)
|
||||||
return unless self.class.respond_to?(:properties)
|
|
||||||
return if self.class.properties.empty?
|
|
||||||
# TODO: cache the default object
|
# TODO: cache the default object
|
||||||
self.class.properties.each do |property|
|
self.class.properties.each do |property|
|
||||||
key = property.name.to_s
|
write_attribute(property, property.default_value)
|
||||||
# let's make sure we have a default
|
|
||||||
unless property.default.nil?
|
|
||||||
if property.default.class == Proc
|
|
||||||
self[key] = property.default.call
|
|
||||||
else
|
|
||||||
self[key] = Marshal.load(Marshal.dump(property.default))
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
def cast_keys
|
|
||||||
return unless self.class.properties
|
|
||||||
self.class.properties.each do |property|
|
|
||||||
cast_property(property)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def cast_property(property, assigned=false)
|
|
||||||
return unless property.casted
|
|
||||||
key = self.has_key?(property.name) ? property.name : property.name.to_sym
|
|
||||||
# Don't cast the property unless it has a value
|
|
||||||
return unless self[key]
|
|
||||||
if property.type.is_a?(Array)
|
|
||||||
klass = property.type[0]
|
|
||||||
self[key] = [self[key]] unless self[key].is_a?(Array)
|
|
||||||
arr = self[key].collect do |value|
|
|
||||||
value = typecast_value(value, klass, property.init_method)
|
|
||||||
associate_casted_to_parent(value, assigned)
|
|
||||||
value
|
|
||||||
end
|
|
||||||
# allow casted_by calls to be passed up chain by wrapping in CastedArray
|
|
||||||
self[key] = klass != String ? ::CouchRest::CastedArray.new(arr) : arr
|
|
||||||
self[key].casted_by = self if self[key].respond_to?(:casted_by)
|
|
||||||
else
|
|
||||||
self[key] = typecast_value(self[key], property.type, property.init_method)
|
|
||||||
associate_casted_to_parent(self[key], assigned)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def associate_casted_to_parent(casted, assigned)
|
|
||||||
casted.casted_by = self if casted.respond_to?(:casted_by)
|
|
||||||
casted.document_saved = true if !assigned && casted.respond_to?(:document_saved)
|
|
||||||
end
|
|
||||||
|
|
||||||
def cast_property_by_name(property_name)
|
|
||||||
return unless self.class.properties
|
|
||||||
property = self.class.properties.detect{|property| property.name == property_name}
|
|
||||||
return unless property
|
|
||||||
cast_property(property, true)
|
|
||||||
end
|
|
||||||
|
|
||||||
|
|
||||||
module ClassMethods
|
module ClassMethods
|
||||||
|
|
||||||
def property(name, *options)
|
def property(name, *options, &block)
|
||||||
opts = { }
|
opts = { }
|
||||||
type = options.shift
|
type = options.shift
|
||||||
if type.class != Hash
|
if type.class != Hash
|
||||||
|
@ -93,21 +56,29 @@ module CouchRest
|
||||||
end
|
end
|
||||||
existing_property = self.properties.find{|p| p.name == name.to_s}
|
existing_property = self.properties.find{|p| p.name == name.to_s}
|
||||||
if existing_property.nil? || (existing_property.default != opts[:default])
|
if existing_property.nil? || (existing_property.default != opts[:default])
|
||||||
define_property(name, opts)
|
define_property(name, opts, &block)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
protected
|
protected
|
||||||
|
|
||||||
# This is not a thread safe operation, if you have to set new properties at runtime
|
# This is not a thread safe operation, if you have to set new properties at runtime
|
||||||
# make sure to use a mutex.
|
# make sure a mutex is used.
|
||||||
def define_property(name, options={})
|
def define_property(name, options={}, &block)
|
||||||
# check if this property is going to casted
|
# check if this property is going to casted
|
||||||
options[:casted] = !!(options[:cast_as] || options[:type])
|
type = options.delete(:type) || options.delete(:cast_as)
|
||||||
property = CouchRest::Property.new(name, (options.delete(:cast_as) || options.delete(:type)), options)
|
if block_given?
|
||||||
|
type = Class.new(Hash) do
|
||||||
|
include CastedModel
|
||||||
|
end
|
||||||
|
type.class_eval { yield type }
|
||||||
|
type = [type] # inject as an array
|
||||||
|
end
|
||||||
|
property = CouchRest::Property.new(name, type, options)
|
||||||
create_property_getter(property)
|
create_property_getter(property)
|
||||||
create_property_setter(property) unless property.read_only == true
|
create_property_setter(property) unless property.read_only == true
|
||||||
properties << property
|
properties << property
|
||||||
|
property
|
||||||
end
|
end
|
||||||
|
|
||||||
# defines the getter for the property (and optional aliases)
|
# defines the getter for the property (and optional aliases)
|
||||||
|
@ -115,18 +86,15 @@ module CouchRest
|
||||||
# meth = property.name
|
# meth = property.name
|
||||||
class_eval <<-EOS, __FILE__, __LINE__ + 1
|
class_eval <<-EOS, __FILE__, __LINE__ + 1
|
||||||
def #{property.name}
|
def #{property.name}
|
||||||
self['#{property.name}']
|
read_attribute('#{property.name}')
|
||||||
end
|
end
|
||||||
EOS
|
EOS
|
||||||
|
|
||||||
if ['boolean', TrueClass.to_s.downcase].include?(property.type.to_s.downcase)
|
if ['boolean', TrueClass.to_s.downcase].include?(property.type.to_s.downcase)
|
||||||
class_eval <<-EOS, __FILE__, __LINE__
|
class_eval <<-EOS, __FILE__, __LINE__
|
||||||
def #{property.name}?
|
def #{property.name}?
|
||||||
if self['#{property.name}'].nil? || self['#{property.name}'] == false
|
value = read_attribute('#{property.name}')
|
||||||
false
|
!(value.nil? || value == false)
|
||||||
else
|
|
||||||
true
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
EOS
|
EOS
|
||||||
end
|
end
|
||||||
|
@ -143,8 +111,7 @@ module CouchRest
|
||||||
property_name = property.name
|
property_name = property.name
|
||||||
class_eval <<-EOS
|
class_eval <<-EOS
|
||||||
def #{property_name}=(value)
|
def #{property_name}=(value)
|
||||||
self['#{property_name}'] = value
|
write_attribute('#{property_name}', value)
|
||||||
cast_property_by_name('#{property_name}')
|
|
||||||
end
|
end
|
||||||
EOS
|
EOS
|
||||||
|
|
||||||
|
|
|
@ -1,7 +1,6 @@
|
||||||
require 'time'
|
require 'time'
|
||||||
require 'bigdecimal'
|
require 'bigdecimal'
|
||||||
require 'bigdecimal/util'
|
require 'bigdecimal/util'
|
||||||
require File.join(File.dirname(__FILE__), 'property')
|
|
||||||
|
|
||||||
class Time
|
class Time
|
||||||
# returns a local time value much faster than Time.parse
|
# returns a local time value much faster than Time.parse
|
||||||
|
@ -23,19 +22,19 @@ class Time
|
||||||
end
|
end
|
||||||
|
|
||||||
module CouchRest
|
module CouchRest
|
||||||
module More
|
module Mixins
|
||||||
module Typecast
|
module Typecast
|
||||||
|
|
||||||
def typecast_value(value, klass, init_method)
|
def typecast_value(value, property) # klass, init_method)
|
||||||
return nil if value.nil?
|
return nil if value.nil?
|
||||||
klass = klass.constantize unless klass.is_a?(Class)
|
klass = property.type_class
|
||||||
if value.instance_of?(klass) || klass == Object
|
if value.instance_of?(klass) || klass == Object
|
||||||
value
|
value
|
||||||
elsif [String, TrueClass, Integer, Float, BigDecimal, DateTime, Time, Date, Class].include?(klass)
|
elsif [String, TrueClass, Integer, Float, BigDecimal, DateTime, Time, Date, Class].include?(klass)
|
||||||
send('typecast_to_'+klass.to_s.downcase, value)
|
send('typecast_to_'+klass.to_s.downcase, value)
|
||||||
else
|
else
|
||||||
# Allow the init_method to be defined as a Proc for advanced conversion
|
# Allow the init_method to be defined as a Proc for advanced conversion
|
||||||
init_method.is_a?(Proc) ? init_method.call(value) : klass.send(init_method, value)
|
property.init_method.is_a?(Proc) ? property.init_method.call(value) : klass.send(property.init_method, value)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
|
@ -1,245 +0,0 @@
|
||||||
# Extracted from dm-validations 0.9.10
|
|
||||||
#
|
|
||||||
# Copyright (c) 2007 Guy van den Berg
|
|
||||||
#
|
|
||||||
# Permission is hereby granted, free of charge, to any person obtaining
|
|
||||||
# a copy of this software and associated documentation files (the
|
|
||||||
# "Software"), to deal in the Software without restriction, including
|
|
||||||
# without limitation the rights to use, copy, modify, merge, publish,
|
|
||||||
# distribute, sublicense, and/or sell copies of the Software, and to
|
|
||||||
# permit persons to whom the Software is furnished to do so, subject to
|
|
||||||
# the following conditions:
|
|
||||||
#
|
|
||||||
# The above copyright notice and this permission notice shall be
|
|
||||||
# included in all copies or substantial portions of the Software.
|
|
||||||
#
|
|
||||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
||||||
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
||||||
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
||||||
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
|
||||||
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
|
||||||
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
|
||||||
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
||||||
|
|
||||||
class Object
|
|
||||||
def validatable?
|
|
||||||
false
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
require 'pathname'
|
|
||||||
|
|
||||||
dir = File.join(Pathname(__FILE__).dirname.expand_path, '..', 'validation')
|
|
||||||
|
|
||||||
require File.join(dir, 'validation_errors')
|
|
||||||
require File.join(dir, 'contextual_validators')
|
|
||||||
require File.join(dir, 'auto_validate')
|
|
||||||
|
|
||||||
require File.join(dir, 'validators', 'generic_validator')
|
|
||||||
require File.join(dir, 'validators', 'required_field_validator')
|
|
||||||
require File.join(dir, 'validators', 'absent_field_validator')
|
|
||||||
require File.join(dir, 'validators', 'format_validator')
|
|
||||||
require File.join(dir, 'validators', 'length_validator')
|
|
||||||
require File.join(dir, 'validators', 'numeric_validator')
|
|
||||||
require File.join(dir, 'validators', 'method_validator')
|
|
||||||
require File.join(dir, 'validators', 'confirmation_validator')
|
|
||||||
|
|
||||||
module CouchRest
|
|
||||||
module Validation
|
|
||||||
|
|
||||||
def self.included(base)
|
|
||||||
base.extlib_inheritable_accessor(:auto_validation)
|
|
||||||
base.class_eval <<-EOS, __FILE__, __LINE__ + 1
|
|
||||||
# Callbacks
|
|
||||||
define_callbacks :validate
|
|
||||||
|
|
||||||
# Turn off auto validation by default
|
|
||||||
self.auto_validation ||= false
|
|
||||||
|
|
||||||
# Force the auto validation for the class properties
|
|
||||||
# This feature is still not fully ported over,
|
|
||||||
# test are lacking, so please use with caution
|
|
||||||
def self.auto_validate!
|
|
||||||
self.auto_validation = true
|
|
||||||
end
|
|
||||||
|
|
||||||
# share the validations with subclasses
|
|
||||||
def self.inherited(subklass)
|
|
||||||
self.validators.contexts.each do |k, v|
|
|
||||||
subklass.validators.contexts[k] = v.dup
|
|
||||||
end
|
|
||||||
super
|
|
||||||
end
|
|
||||||
EOS
|
|
||||||
|
|
||||||
base.extend(ClassMethods)
|
|
||||||
base.class_eval <<-EOS, __FILE__, __LINE__ + 1
|
|
||||||
define_callbacks :validate
|
|
||||||
if method_defined?(:_run_save_callbacks)
|
|
||||||
set_callback :save, :before, :check_validations
|
|
||||||
end
|
|
||||||
EOS
|
|
||||||
base.class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
|
|
||||||
def self.define_property(name, options={})
|
|
||||||
super
|
|
||||||
auto_generate_validations(properties.last) if properties && properties.size > 0
|
|
||||||
autovalidation_check = true
|
|
||||||
end
|
|
||||||
RUBY_EVAL
|
|
||||||
end
|
|
||||||
|
|
||||||
# Ensures the object is valid for the context provided, and otherwise
|
|
||||||
# throws :halt and returns false.
|
|
||||||
#
|
|
||||||
def check_validations(context = :default)
|
|
||||||
throw(:halt, false) unless context.nil? || valid?(context)
|
|
||||||
end
|
|
||||||
|
|
||||||
# Return the ValidationErrors
|
|
||||||
#
|
|
||||||
def errors
|
|
||||||
@errors ||= ValidationErrors.new
|
|
||||||
end
|
|
||||||
|
|
||||||
# Mark this resource as validatable. When we validate associations of a
|
|
||||||
# resource we can check if they respond to validatable? before trying to
|
|
||||||
# recursivly validate them
|
|
||||||
#
|
|
||||||
def validatable?
|
|
||||||
true
|
|
||||||
end
|
|
||||||
|
|
||||||
# Alias for valid?(:default)
|
|
||||||
#
|
|
||||||
def valid_for_default?
|
|
||||||
valid?(:default)
|
|
||||||
end
|
|
||||||
|
|
||||||
# Check if a resource is valid in a given context
|
|
||||||
#
|
|
||||||
def valid?(context = :default)
|
|
||||||
recursive_valid?(self, context, true)
|
|
||||||
end
|
|
||||||
|
|
||||||
# checking on casted objects
|
|
||||||
def validate_casted_arrays
|
|
||||||
result = true
|
|
||||||
array_casted_properties = self.class.properties.select { |property| property.casted && property.type.instance_of?(Array) }
|
|
||||||
array_casted_properties.each do |property|
|
|
||||||
casted_values = self.send(property.name)
|
|
||||||
next unless casted_values.is_a?(Array) && casted_values.first.respond_to?(:valid?)
|
|
||||||
casted_values.each do |value|
|
|
||||||
result = (result && value.valid?) if value.respond_to?(:valid?)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
result
|
|
||||||
end
|
|
||||||
|
|
||||||
# Do recursive validity checking
|
|
||||||
#
|
|
||||||
def recursive_valid?(target, context, state)
|
|
||||||
valid = state
|
|
||||||
target.each do |key, prop|
|
|
||||||
if prop.is_a?(Array)
|
|
||||||
prop.each do |item|
|
|
||||||
if item.validatable?
|
|
||||||
valid = recursive_valid?(item, context, valid) && valid
|
|
||||||
end
|
|
||||||
end
|
|
||||||
elsif prop.validatable?
|
|
||||||
valid = recursive_valid?(prop, context, valid) && valid
|
|
||||||
end
|
|
||||||
end
|
|
||||||
target._run_validate_callbacks do
|
|
||||||
target.class.validators.execute(context, target) && valid
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
|
|
||||||
def validation_property_value(name)
|
|
||||||
self.respond_to?(name, true) ? self.send(name) : nil
|
|
||||||
end
|
|
||||||
|
|
||||||
# Get the corresponding Object property, if it exists.
|
|
||||||
def validation_property(field_name)
|
|
||||||
properties.find{|p| p.name == field_name}
|
|
||||||
end
|
|
||||||
|
|
||||||
module ClassMethods
|
|
||||||
include CouchRest::Validation::ValidatesPresent
|
|
||||||
include CouchRest::Validation::ValidatesAbsent
|
|
||||||
include CouchRest::Validation::ValidatesIsConfirmed
|
|
||||||
# include CouchRest::Validation::ValidatesIsPrimitive
|
|
||||||
# include CouchRest::Validation::ValidatesIsAccepted
|
|
||||||
include CouchRest::Validation::ValidatesFormat
|
|
||||||
include CouchRest::Validation::ValidatesLength
|
|
||||||
# include CouchRest::Validation::ValidatesWithin
|
|
||||||
include CouchRest::Validation::ValidatesIsNumber
|
|
||||||
include CouchRest::Validation::ValidatesWithMethod
|
|
||||||
# include CouchRest::Validation::ValidatesWithBlock
|
|
||||||
# include CouchRest::Validation::ValidatesIsUnique
|
|
||||||
include CouchRest::Validation::AutoValidate
|
|
||||||
|
|
||||||
# Return the set of contextual validators or create a new one
|
|
||||||
#
|
|
||||||
def validators
|
|
||||||
@validations ||= ContextualValidators.new
|
|
||||||
end
|
|
||||||
|
|
||||||
# Clean up the argument list and return a opts hash, including the
|
|
||||||
# merging of any default opts. Set the context to default if none is
|
|
||||||
# provided. Also allow :context to be aliased to :on, :when & group
|
|
||||||
#
|
|
||||||
def opts_from_validator_args(args, defaults = nil)
|
|
||||||
opts = args.last.kind_of?(Hash) ? args.pop : {}
|
|
||||||
context = :default
|
|
||||||
context = opts[:context] if opts.has_key?(:context)
|
|
||||||
context = opts.delete(:on) if opts.has_key?(:on)
|
|
||||||
context = opts.delete(:when) if opts.has_key?(:when)
|
|
||||||
context = opts.delete(:group) if opts.has_key?(:group)
|
|
||||||
opts[:context] = context
|
|
||||||
opts.merge!(defaults) unless defaults.nil?
|
|
||||||
opts
|
|
||||||
end
|
|
||||||
|
|
||||||
# Given a new context create an instance method of
|
|
||||||
# valid_for_<context>? which simply calls valid?(context)
|
|
||||||
# if it does not already exist
|
|
||||||
#
|
|
||||||
def create_context_instance_methods(context)
|
|
||||||
name = "valid_for_#{context.to_s}?" # valid_for_signup?
|
|
||||||
if !self.instance_methods.include?(name)
|
|
||||||
class_eval <<-EOS, __FILE__, __LINE__ + 1
|
|
||||||
def #{name} # def valid_for_signup?
|
|
||||||
valid?('#{context.to_s}'.to_sym) # valid?('signup'.to_sym)
|
|
||||||
end # end
|
|
||||||
EOS
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# Create a new validator of the given klazz and push it onto the
|
|
||||||
# requested context for each of the attributes in the fields list
|
|
||||||
#
|
|
||||||
def add_validator_to_context(opts, fields, klazz)
|
|
||||||
fields.each do |field|
|
|
||||||
validator = klazz.new(field.to_sym, opts)
|
|
||||||
if opts[:context].is_a?(Symbol)
|
|
||||||
unless validators.context(opts[:context]).include?(validator)
|
|
||||||
validators.context(opts[:context]) << validator
|
|
||||||
create_context_instance_methods(opts[:context])
|
|
||||||
end
|
|
||||||
elsif opts[:context].is_a?(Array)
|
|
||||||
opts[:context].each do |c|
|
|
||||||
unless validators.context(c).include?(validator)
|
|
||||||
validators.context(c) << validator
|
|
||||||
create_context_instance_methods(c)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
end # module ClassMethods
|
|
||||||
end # module Validation
|
|
||||||
|
|
||||||
end # module CouchRest
|
|
|
@ -1,22 +1,81 @@
|
||||||
|
|
||||||
|
require File.join(File.dirname(__FILE__), 'mixins', 'typecast')
|
||||||
|
|
||||||
module CouchRest
|
module CouchRest
|
||||||
|
|
||||||
# Basic attribute support for adding getter/setter + validation
|
# Basic attribute support for adding getter/setter + validation
|
||||||
class Property
|
class Property
|
||||||
|
|
||||||
|
include ::CouchRest::Mixins::Typecast
|
||||||
|
|
||||||
attr_reader :name, :type, :read_only, :alias, :default, :casted, :init_method, :options
|
attr_reader :name, :type, :read_only, :alias, :default, :casted, :init_method, :options
|
||||||
|
|
||||||
# attribute to define
|
# Attribute to define.
|
||||||
|
# All Properties are assumed casted unless the type is nil.
|
||||||
def initialize(name, type = nil, options = {})
|
def initialize(name, type = nil, options = {})
|
||||||
@name = name.to_s
|
@name = name.to_s
|
||||||
|
@casted = true
|
||||||
parse_type(type)
|
parse_type(type)
|
||||||
parse_options(options)
|
parse_options(options)
|
||||||
self
|
self
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def to_s
|
||||||
|
name
|
||||||
|
end
|
||||||
|
|
||||||
|
# Cast the provided value using the properties details.
|
||||||
|
def cast(parent, value)
|
||||||
|
return value unless casted
|
||||||
|
if type.is_a?(Array)
|
||||||
|
# Convert to array if it is not already
|
||||||
|
value = [value].compact unless value.is_a?(Array)
|
||||||
|
arr = value.collect { |data| cast_value(parent, data) }
|
||||||
|
# allow casted_by calls to be passed up chain by wrapping in CastedArray
|
||||||
|
value = type_class != String ? ::CouchRest::CastedArray.new(arr, self) : arr
|
||||||
|
value.casted_by = parent if value.respond_to?(:casted_by)
|
||||||
|
elsif !value.nil?
|
||||||
|
value = cast_value(parent, value)
|
||||||
|
end
|
||||||
|
value
|
||||||
|
end
|
||||||
|
|
||||||
|
# Cast an individual value, not an array
|
||||||
|
def cast_value(parent, value)
|
||||||
|
raise "An array inside an array cannot be casted, use CastedModel" if value.is_a?(Array)
|
||||||
|
value = typecast_value(value, self)
|
||||||
|
associate_casted_value_to_parent(parent, value)
|
||||||
|
end
|
||||||
|
|
||||||
|
def default_value
|
||||||
|
return if default.nil?
|
||||||
|
if default.class == Proc
|
||||||
|
default.call
|
||||||
|
else
|
||||||
|
Marshal.load(Marshal.dump(default))
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
# Always provide the basic type as a class. If the type
|
||||||
|
# is an array, the class will be extracted.
|
||||||
|
def type_class
|
||||||
|
return String unless casted # This is rubbish, to handle validations
|
||||||
|
return @type_class unless @type_class.nil?
|
||||||
|
base = @type.is_a?(Array) ? @type.first : @type
|
||||||
|
@type_class = base.is_a?(Class) ? base : base.constantize
|
||||||
|
end
|
||||||
|
|
||||||
private
|
private
|
||||||
|
|
||||||
|
def associate_casted_value_to_parent(parent, value)
|
||||||
|
value.casted_by = parent if value.respond_to?(:casted_by)
|
||||||
|
value
|
||||||
|
end
|
||||||
|
|
||||||
def parse_type(type)
|
def parse_type(type)
|
||||||
if type.nil?
|
if type.nil?
|
||||||
@type = String
|
@casted = false
|
||||||
|
@type = nil
|
||||||
elsif type.is_a?(Array) && type.empty?
|
elsif type.is_a?(Array) && type.empty?
|
||||||
@type = [Object]
|
@type = [Object]
|
||||||
else
|
else
|
||||||
|
@ -36,12 +95,10 @@ module CouchRest
|
||||||
end
|
end
|
||||||
|
|
||||||
def parse_options(options)
|
def parse_options(options)
|
||||||
return if options.empty?
|
|
||||||
@validation_format = options.delete(:format) if options[:format]
|
@validation_format = options.delete(:format) if options[:format]
|
||||||
@read_only = options.delete(:read_only) if options[:read_only]
|
@read_only = options.delete(:read_only) if options[:read_only]
|
||||||
@alias = options.delete(:alias) if options[:alias]
|
@alias = options.delete(:alias) if options[:alias]
|
||||||
@default = options.delete(:default) unless options[:default].nil?
|
@default = options.delete(:default) unless options[:default].nil?
|
||||||
@casted = options[:casted] ? true : false
|
|
||||||
@init_method = options[:init_method] ? options.delete(:init_method) : 'new'
|
@init_method = options[:init_method] ? options.delete(:init_method) : 'new'
|
||||||
@options = options
|
@options = options
|
||||||
end
|
end
|
||||||
|
|
|
@ -80,10 +80,9 @@ module CouchRest
|
||||||
end
|
end
|
||||||
EOS
|
EOS
|
||||||
base.class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
|
base.class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
|
||||||
def self.define_property(name, options={})
|
def self.define_property(name, options={}, &block)
|
||||||
super
|
property = super
|
||||||
auto_generate_validations(properties.last) if properties && properties.size > 0
|
auto_generate_validations(property) unless property.nil?
|
||||||
autovalidation_check = true
|
|
||||||
end
|
end
|
||||||
RUBY_EVAL
|
RUBY_EVAL
|
||||||
end
|
end
|
||||||
|
|
|
@ -100,7 +100,7 @@ module CouchRest
|
||||||
end
|
end
|
||||||
|
|
||||||
# length
|
# length
|
||||||
if property.type == String
|
if property.type_class == String
|
||||||
# XXX: maybe length should always return a Range, with the min defaulting to 1
|
# XXX: maybe length should always return a Range, with the min defaulting to 1
|
||||||
# 52 being the max set
|
# 52 being the max set
|
||||||
len = property.options.fetch(:length, property.options.fetch(:size, 52))
|
len = property.options.fetch(:length, property.options.fetch(:size, 52))
|
||||||
|
@ -137,16 +137,16 @@ module CouchRest
|
||||||
end
|
end
|
||||||
|
|
||||||
# numeric validator
|
# numeric validator
|
||||||
if "Integer" == property.type
|
if property.type_class == Integer
|
||||||
opts[:integer_only] = true
|
opts[:integer_only] = true
|
||||||
validates_numericality_of property.name, options_with_message(opts, property, :is_number)
|
validates_numericality_of property.name, options_with_message(opts, property, :is_number)
|
||||||
elsif Float == property.type
|
elsif Float == property.type_class
|
||||||
opts[:precision] = property.precision
|
opts[:precision] = property.precision
|
||||||
opts[:scale] = property.scale
|
opts[:scale] = property.scale
|
||||||
validates_numericality_of property.name, options_with_message(opts, property, :is_number)
|
validates_numericality_of property.name, options_with_message(opts, property, :is_number)
|
||||||
end
|
end
|
||||||
|
|
||||||
# marked the property has checked
|
# marked the property as checked
|
||||||
property.autovalidation_check = true
|
property.autovalidation_check = true
|
||||||
|
|
||||||
end
|
end
|
||||||
|
|
|
@ -19,8 +19,11 @@ end
|
||||||
class DummyModel < CouchRest::ExtendedDocument
|
class DummyModel < CouchRest::ExtendedDocument
|
||||||
use_database TEST_SERVER.default_database
|
use_database TEST_SERVER.default_database
|
||||||
raise "Default DB not set" if TEST_SERVER.default_database.nil?
|
raise "Default DB not set" if TEST_SERVER.default_database.nil?
|
||||||
property :casted_attribute, :cast_as => 'WithCastedModelMixin'
|
property :casted_attribute, WithCastedModelMixin
|
||||||
property :keywords, :cast_as => ["String"]
|
property :keywords, ["String"]
|
||||||
|
property :sub_models do |child|
|
||||||
|
child.property :title
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
class CastedCallbackDoc < CouchRest::ExtendedDocument
|
class CastedCallbackDoc < CouchRest::ExtendedDocument
|
||||||
|
@ -82,6 +85,20 @@ describe CouchRest::CastedModel do
|
||||||
@casted_obj.should == nil
|
@casted_obj.should == nil
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
describe "anonymous sub casted models" do
|
||||||
|
before :each do
|
||||||
|
@obj = DummyModel.new
|
||||||
|
end
|
||||||
|
it "should be empty initially" do
|
||||||
|
@obj.sub_models.should_not be_nil
|
||||||
|
@obj.sub_models.should be_empty
|
||||||
|
end
|
||||||
|
it "should be updatable using a hash" do
|
||||||
|
@obj.sub_models << {:title => 'test'}
|
||||||
|
@obj.sub_models.first.title.should eql('test')
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
describe "casted as attribute" do
|
describe "casted as attribute" do
|
||||||
before(:each) do
|
before(:each) do
|
||||||
|
@ -308,6 +325,7 @@ describe CouchRest::CastedModel do
|
||||||
@cat.create
|
@cat.create
|
||||||
@cat.save
|
@cat.save
|
||||||
@cat.favorite_toy.should_not be_new
|
@cat.favorite_toy.should_not be_new
|
||||||
|
@cat.toys.first.casted_by.should eql(@cat)
|
||||||
@cat.toys.first.should_not be_new
|
@cat.toys.first.should_not be_new
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|
|
@ -226,18 +226,19 @@ describe "ExtendedDocument" do
|
||||||
@art['title'].should == "something else"
|
@art['title'].should == "something else"
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should flip out if an attribute= method is missing" do
|
it "should not flip out if an attribute= method is missing and ignore it" do
|
||||||
lambda {
|
lambda {
|
||||||
@art.update_attributes_without_saving('slug' => "new-slug", :title => "super danger")
|
@art.update_attributes_without_saving('slug' => "new-slug", :title => "super danger")
|
||||||
}.should raise_error
|
}.should_not raise_error
|
||||||
|
@art.slug.should == "big-bad-danger"
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should not change other attributes if there is an error" do
|
#it "should not change other attributes if there is an error" do
|
||||||
lambda {
|
# lambda {
|
||||||
@art.update_attributes_without_saving('slug' => "new-slug", :title => "super danger")
|
# @art.update_attributes_without_saving('slug' => "new-slug", :title => "super danger")
|
||||||
}.should raise_error
|
# }.should raise_error
|
||||||
@art['title'].should == "big bad danger"
|
# @art['title'].should == "big bad danger"
|
||||||
end
|
#end
|
||||||
end
|
end
|
||||||
|
|
||||||
describe "update attributes" do
|
describe "update attributes" do
|
||||||
|
|
5
spec/fixtures/more/question.rb
vendored
5
spec/fixtures/more/question.rb
vendored
|
@ -2,5 +2,6 @@ class Question < Hash
|
||||||
include ::CouchRest::CastedModel
|
include ::CouchRest::CastedModel
|
||||||
|
|
||||||
property :q
|
property :q
|
||||||
property :a, :type => 'Object'
|
property :a
|
||||||
end
|
|
||||||
|
end
|
||||||
|
|
Loading…
Add table
Reference in a new issue