This commit is contained in:
Sam Lown 2010-06-16 21:04:53 +02:00
parent b7593006c8
commit 2b0694e1e2
15 changed files with 422 additions and 435 deletions

View 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

View file

@ -1,7 +1,6 @@
require 'time'
require File.join(File.dirname(__FILE__), '..', 'property')
require File.join(File.dirname(__FILE__), '..', 'casted_array')
require File.join(File.dirname(__FILE__), '..', 'typecast')
module CouchRest
module Mixins
@ -9,8 +8,6 @@ module CouchRest
class IncludeError < StandardError; end
include ::CouchRest::More::Typecast
def self.included(base)
base.class_eval <<-EOS, __FILE__, __LINE__ + 1
extlib_inheritable_accessor(:properties) unless self.respond_to?(:properties)
@ -19,70 +16,36 @@ module CouchRest
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?(:[]=))
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 unless self.class.respond_to?(:properties)
return if self.class.properties.empty?
# TODO: cache the default object
self.class.properties.each do |property|
key = property.name.to_s
# 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
write_attribute(property, property.default_value)
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
def property(name, *options)
def property(name, *options, &block)
opts = { }
type = options.shift
if type.class != Hash
@ -93,21 +56,29 @@ module CouchRest
end
existing_property = self.properties.find{|p| p.name == name.to_s}
if existing_property.nil? || (existing_property.default != opts[:default])
define_property(name, opts)
define_property(name, opts, &block)
end
end
protected
# This is not a thread safe operation, if you have to set new properties at runtime
# make sure to use a mutex.
def define_property(name, options={})
# make sure a mutex is used.
def define_property(name, options={}, &block)
# check if this property is going to casted
options[:casted] = !!(options[:cast_as] || options[:type])
property = CouchRest::Property.new(name, (options.delete(:cast_as) || options.delete(:type)), options)
type = options.delete(:type) || options.delete(:cast_as)
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_setter(property) unless property.read_only == true
properties << property
property
end
# defines the getter for the property (and optional aliases)
@ -115,18 +86,15 @@ module CouchRest
# meth = property.name
class_eval <<-EOS, __FILE__, __LINE__ + 1
def #{property.name}
self['#{property.name}']
read_attribute('#{property.name}')
end
EOS
if ['boolean', TrueClass.to_s.downcase].include?(property.type.to_s.downcase)
class_eval <<-EOS, __FILE__, __LINE__
def #{property.name}?
if self['#{property.name}'].nil? || self['#{property.name}'] == false
false
else
true
end
value = read_attribute('#{property.name}')
!(value.nil? || value == false)
end
EOS
end
@ -143,8 +111,7 @@ module CouchRest
property_name = property.name
class_eval <<-EOS
def #{property_name}=(value)
self['#{property_name}'] = value
cast_property_by_name('#{property_name}')
write_attribute('#{property_name}', value)
end
EOS

View file

@ -0,0 +1,174 @@
require 'time'
require 'bigdecimal'
require 'bigdecimal/util'
class Time
# returns a local time value much faster than Time.parse
def self.mktime_with_offset(string)
string =~ /(\d{4})[\-|\/](\d{2})[\-|\/](\d{2})[T|\s](\d{2}):(\d{2}):(\d{2})([\+|\s|\-])*(\d{2}):?(\d{2})/
# $1 = year
# $2 = month
# $3 = day
# $4 = hours
# $5 = minutes
# $6 = seconds
# $7 = time zone direction
# $8 = tz difference
# utc time with wrong TZ info:
time = mktime($1, RFC2822_MONTH_NAME[$2.to_i - 1], $3, $4, $5, $6, $7)
tz_difference = ("#{$7 == '-' ? '+' : '-'}#{$8}".to_i * 3600)
time + tz_difference + zone_offset(time.zone)
end
end
module CouchRest
module Mixins
module Typecast
def typecast_value(value, property) # klass, init_method)
return nil if value.nil?
klass = property.type_class
if value.instance_of?(klass) || klass == Object
value
elsif [String, TrueClass, Integer, Float, BigDecimal, DateTime, Time, Date, Class].include?(klass)
send('typecast_to_'+klass.to_s.downcase, value)
else
# Allow the init_method to be defined as a Proc for advanced conversion
property.init_method.is_a?(Proc) ? property.init_method.call(value) : klass.send(property.init_method, value)
end
end
protected
# Typecast a value to an Integer
def typecast_to_integer(value)
typecast_to_numeric(value, :to_i)
end
# Typecast a value to a String
def typecast_to_string(value)
value.to_s
end
# Typecast a value to a true or false
def typecast_to_trueclass(value)
if value.kind_of?(Integer)
return true if value == 1
return false if value == 0
elsif value.respond_to?(:to_s)
return true if %w[ true 1 t ].include?(value.to_s.downcase)
return false if %w[ false 0 f ].include?(value.to_s.downcase)
end
value
end
# Typecast a value to a BigDecimal
def typecast_to_bigdecimal(value)
if value.kind_of?(Integer)
value.to_s.to_d
else
typecast_to_numeric(value, :to_d)
end
end
# Typecast a value to a Float
def typecast_to_float(value)
typecast_to_numeric(value, :to_f)
end
# Match numeric string
def typecast_to_numeric(value, method)
if value.respond_to?(:to_str)
if value.to_str =~ /\A(-?(?:0|[1-9]\d*)(?:\.\d+)?|(?:\.\d+))\z/
$1.send(method)
else
value
end
elsif value.respond_to?(method)
value.send(method)
else
value
end
end
# Typecasts an arbitrary value to a DateTime.
# Handles both Hashes and DateTime instances.
# This is slow!! Use Time instead.
def typecast_to_datetime(value)
if value.is_a?(Hash)
typecast_hash_to_datetime(value)
else
DateTime.parse(value.to_s)
end
rescue ArgumentError
value
end
# Typecasts an arbitrary value to a Date
# Handles both Hashes and Date instances.
def typecast_to_date(value)
if value.is_a?(Hash)
typecast_hash_to_date(value)
elsif value.is_a?(Time) # sometimes people think date is time!
value.to_date
elsif value.to_s =~ /(\d{4})[\-|\/](\d{2})[\-|\/](\d{2})/
# Faster than parsing the date
Date.new($1.to_i, $2.to_i, $3.to_i)
else
Date.parse(value)
end
rescue ArgumentError
value
end
# Typecasts an arbitrary value to a Time
# Handles both Hashes and Time instances.
def typecast_to_time(value)
if value.is_a?(Hash)
typecast_hash_to_time(value)
else
Time.mktime_with_offset(value.to_s)
end
rescue ArgumentError
value
rescue TypeError
value
end
# Creates a DateTime instance from a Hash with keys :year, :month, :day,
# :hour, :min, :sec
def typecast_hash_to_datetime(value)
DateTime.new(*extract_time(value))
end
# Creates a Date instance from a Hash with keys :year, :month, :day
def typecast_hash_to_date(value)
Date.new(*extract_time(value)[0, 3])
end
# Creates a Time instance from a Hash with keys :year, :month, :day,
# :hour, :min, :sec
def typecast_hash_to_time(value)
Time.local(*extract_time(value))
end
# Extracts the given args from the hash. If a value does not exist, it
# uses the value of Time.now.
def extract_time(value)
now = Time.now
[:year, :month, :day, :hour, :min, :sec].map do |segment|
typecast_to_numeric(value.fetch(segment, now.send(segment)), :to_i)
end
end
# Typecast a value to a Class
def typecast_to_class(value)
value.to_s.constantize
rescue NameError
value
end
end
end
end

View file

@ -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