adding rdoc to method properties_with_values
This commit is contained in:
commit
92a10dbfc9
30 changed files with 764 additions and 506 deletions
|
@ -1,132 +0,0 @@
|
|||
module CouchRest
|
||||
module Model
|
||||
ReadOnlyPropertyError = Class.new(StandardError)
|
||||
|
||||
# Attributes Suffixes provide methods from ActiveModel
|
||||
# to hook into. See methods such as #attribute= and
|
||||
# #attribute? for their implementation
|
||||
AttributeMethodSuffixes = ['', '=', '?']
|
||||
|
||||
module Attributes
|
||||
extend ActiveSupport::Concern
|
||||
|
||||
included do
|
||||
include ActiveModel::AttributeMethods
|
||||
attribute_method_suffix *AttributeMethodSuffixes
|
||||
end
|
||||
|
||||
module ClassMethods
|
||||
def attributes
|
||||
properties.map {|prop| prop.name}
|
||||
end
|
||||
end
|
||||
|
||||
def initialize(*args)
|
||||
self.class.attribute_method_suffix *AttributeMethodSuffixes
|
||||
super
|
||||
end
|
||||
|
||||
def attributes
|
||||
self.class.attributes
|
||||
end
|
||||
|
||||
## Reads the attribute value.
|
||||
# Assuming you have a property :title this would be called
|
||||
# by `model_instance.title`
|
||||
def attribute(name)
|
||||
read_attribute(name)
|
||||
end
|
||||
|
||||
## Sets the attribute value.
|
||||
# Assuming you have a property :title this would be called
|
||||
# by `model_instance.title = 'hello'`
|
||||
def attribute=(name, value)
|
||||
raise ReadOnlyPropertyError, 'read only property' if find_property!(name).read_only
|
||||
write_attribute(name, value)
|
||||
end
|
||||
|
||||
## Tests for both presence and truthiness of the attribute.
|
||||
# Assuming you have a property :title # this would be called
|
||||
# by `model_instance.title?`
|
||||
def attribute?(name)
|
||||
value = read_attribute(name)
|
||||
!(value.nil? || value == false)
|
||||
end
|
||||
|
||||
## 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
|
||||
|
||||
def read_attribute(property)
|
||||
prop = find_property!(property)
|
||||
self[prop.to_s]
|
||||
end
|
||||
|
||||
def write_attribute(property, value)
|
||||
prop = find_property!(property)
|
||||
self[prop.to_s] = prop.cast(self, value)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def read_only_attributes
|
||||
properties.select { |prop| prop.read_only }.map { |prop| prop.name }
|
||||
end
|
||||
|
||||
def directly_set_attributes(hash)
|
||||
r_o_a = read_only_attributes
|
||||
hash.each do |attribute_name, attribute_value|
|
||||
next if r_o_a.include? attribute_name
|
||||
if self.respond_to?("#{attribute_name}=")
|
||||
self.send("#{attribute_name}=", hash.delete(attribute_name))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def directly_set_read_only_attributes(hash)
|
||||
r_o_a = read_only_attributes
|
||||
property_list = attributes
|
||||
hash.each do |attribute_name, attribute_value|
|
||||
next unless r_o_a.include? 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 = attributes
|
||||
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
|
||||
|
|
@ -4,24 +4,23 @@ module CouchRest
|
|||
|
||||
extend ActiveModel::Naming
|
||||
|
||||
include CouchRest::Model::Configuration
|
||||
include CouchRest::Model::Persistence
|
||||
include CouchRest::Model::Callbacks
|
||||
include CouchRest::Model::DocumentQueries
|
||||
include CouchRest::Model::DocumentQueries
|
||||
include CouchRest::Model::Views
|
||||
include CouchRest::Model::DesignDoc
|
||||
include CouchRest::Model::ExtendedAttachments
|
||||
include CouchRest::Model::ClassProxy
|
||||
include CouchRest::Model::Collection
|
||||
include CouchRest::Model::AttributeProtection
|
||||
include CouchRest::Model::Attributes
|
||||
include CouchRest::Model::PropertyProtection
|
||||
include CouchRest::Model::Associations
|
||||
include CouchRest::Model::Validations
|
||||
include CouchRest::Model::Dirty
|
||||
|
||||
def self.subclasses
|
||||
@subclasses ||= []
|
||||
end
|
||||
|
||||
|
||||
def self.inherited(subklass)
|
||||
super
|
||||
subklass.send(:include, CouchRest::Model::Properties)
|
||||
|
@ -35,7 +34,7 @@ module CouchRest
|
|||
EOS
|
||||
subclasses << subklass
|
||||
end
|
||||
|
||||
|
||||
# Accessors
|
||||
attr_accessor :casted_by
|
||||
|
||||
|
@ -44,19 +43,19 @@ module CouchRest
|
|||
# using the provided document hash.
|
||||
#
|
||||
# Options supported:
|
||||
#
|
||||
#
|
||||
# * :directly_set_attributes: true when data comes directly from database
|
||||
#
|
||||
def initialize(doc = {}, options = {})
|
||||
prepare_all_attributes(doc, options)
|
||||
doc = prepare_all_attributes(doc, options)
|
||||
super(doc)
|
||||
unless self['_id'] && self['_rev']
|
||||
self['couchrest-type'] = self.class.to_s
|
||||
self[self.model_type_key] = self.class.to_s
|
||||
end
|
||||
after_initialize if respond_to?(:after_initialize)
|
||||
end
|
||||
|
||||
|
||||
|
||||
|
||||
# Temp solution to make the view_by methods available
|
||||
def self.method_missing(m, *args, &block)
|
||||
if has_view?(m)
|
||||
|
@ -70,9 +69,9 @@ module CouchRest
|
|||
end
|
||||
super
|
||||
end
|
||||
|
||||
|
||||
### instance methods
|
||||
|
||||
|
||||
# Gets a reference to the actual document in the DB
|
||||
# Calls up to the next document if there is one,
|
||||
# Otherwise we're at the top and we return self
|
||||
|
@ -80,14 +79,14 @@ module CouchRest
|
|||
return self if base_doc?
|
||||
@casted_by.base_doc
|
||||
end
|
||||
|
||||
|
||||
# Checks if we're the top document
|
||||
def base_doc?
|
||||
!@casted_by
|
||||
end
|
||||
|
||||
|
||||
## Compatibility with ActiveSupport and older frameworks
|
||||
|
||||
|
||||
# Hack so that CouchRest::Document, which descends from Hash,
|
||||
# doesn't appear to Rails routing as a Hash of options
|
||||
def is_a?(klass)
|
||||
|
@ -99,14 +98,14 @@ module CouchRest
|
|||
def persisted?
|
||||
!new?
|
||||
end
|
||||
|
||||
|
||||
def to_key
|
||||
new? ? nil : [id]
|
||||
new? ? nil : [id]
|
||||
end
|
||||
|
||||
alias :to_param :id
|
||||
alias :new_record? :new?
|
||||
alias :new_document? :new?
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
|
@ -1,39 +1,39 @@
|
|||
module CouchRest::Model
|
||||
module CastedModel
|
||||
|
||||
|
||||
extend ActiveSupport::Concern
|
||||
|
||||
included do
|
||||
include CouchRest::Model::AttributeProtection
|
||||
include CouchRest::Model::Attributes
|
||||
include CouchRest::Model::Configuration
|
||||
include CouchRest::Model::Callbacks
|
||||
include CouchRest::Model::Properties
|
||||
include CouchRest::Model::PropertyProtection
|
||||
include CouchRest::Model::Associations
|
||||
include CouchRest::Model::Validations
|
||||
attr_accessor :casted_by
|
||||
end
|
||||
|
||||
|
||||
def initialize(keys = {})
|
||||
raise StandardError unless self.is_a? Hash
|
||||
prepare_all_attributes(keys)
|
||||
super()
|
||||
end
|
||||
|
||||
|
||||
def []= key, value
|
||||
super(key.to_s, value)
|
||||
end
|
||||
|
||||
|
||||
def [] key
|
||||
super(key.to_s)
|
||||
end
|
||||
|
||||
|
||||
# Gets a reference to the top level extended
|
||||
# document that a model is saved inside of
|
||||
def base_doc
|
||||
return nil unless @casted_by
|
||||
@casted_by.base_doc
|
||||
end
|
||||
|
||||
|
||||
# False if the casted model has already
|
||||
# been saved in the containing document
|
||||
def new?
|
||||
|
@ -53,12 +53,12 @@ module CouchRest::Model
|
|||
end
|
||||
alias :to_key :id
|
||||
alias :to_param :id
|
||||
|
||||
|
||||
# Sets the attributes from a hash
|
||||
def update_attributes_without_saving(hash)
|
||||
hash.each do |k, v|
|
||||
raise NoMethodError, "#{k}= method not available, use property :#{k}" unless self.respond_to?("#{k}=")
|
||||
end
|
||||
end
|
||||
hash.each do |k, v|
|
||||
self.send("#{k}=",v)
|
||||
end
|
||||
|
|
|
@ -82,6 +82,7 @@ module CouchRest
|
|||
design_doc['views'][view_name.to_s] &&
|
||||
design_doc['views'][view_name.to_s]["couchrest-defaults"]) || {}
|
||||
view_options = default_view_options.merge(options)
|
||||
view_options.delete(:database)
|
||||
|
||||
[design_doc, view_name, view_options]
|
||||
end
|
||||
|
@ -94,6 +95,8 @@ module CouchRest
|
|||
raise ArgumentError, 'search_name is required' if search_name.nil?
|
||||
|
||||
search_options = options.clone
|
||||
search_options.delete(:database)
|
||||
|
||||
[design_doc, search_name, search_options]
|
||||
end
|
||||
|
||||
|
|
51
lib/couchrest/model/configuration.rb
Normal file
51
lib/couchrest/model/configuration.rb
Normal file
|
@ -0,0 +1,51 @@
|
|||
module CouchRest
|
||||
|
||||
# CouchRest Model Configuration support, stolen from Carrierwave by jnicklas
|
||||
# http://github.com/jnicklas/carrierwave/blob/master/lib/carrierwave/uploader/configuration.rb
|
||||
|
||||
module Model
|
||||
module Configuration
|
||||
extend ActiveSupport::Concern
|
||||
|
||||
included do
|
||||
add_config :model_type_key
|
||||
add_config :mass_assign_any_attribute
|
||||
|
||||
configure do |config|
|
||||
config.model_type_key = 'couchrest-type' # 'model'?
|
||||
config.mass_assign_any_attribute = false
|
||||
end
|
||||
end
|
||||
|
||||
module ClassMethods
|
||||
|
||||
def add_config(name)
|
||||
class_eval <<-RUBY, __FILE__, __LINE__ + 1
|
||||
def self.#{name}(value=nil)
|
||||
@#{name} = value if value
|
||||
return @#{name} if self.object_id == #{self.object_id} || defined?(@#{name})
|
||||
name = superclass.#{name}
|
||||
return nil if name.nil? && !instance_variable_defined?("@#{name}")
|
||||
@#{name} = name && !name.is_a?(Module) && !name.is_a?(Symbol) && !name.is_a?(Numeric) && !name.is_a?(TrueClass) && !name.is_a?(FalseClass) ? name.dup : name
|
||||
end
|
||||
|
||||
def self.#{name}=(value)
|
||||
@#{name} = value
|
||||
end
|
||||
|
||||
def #{name}
|
||||
self.class.#{name}
|
||||
end
|
||||
RUBY
|
||||
end
|
||||
|
||||
def configure
|
||||
yield self
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
|
|
@ -31,7 +31,7 @@ module CouchRest
|
|||
"views" => {
|
||||
'all' => {
|
||||
'map' => "function(doc) {
|
||||
if (doc['couchrest-type'] == '#{self.to_s}') {
|
||||
if (doc['#{self.model_type_key}'] == '#{self.to_s}') {
|
||||
emit(doc['_id'],1);
|
||||
}
|
||||
}"
|
||||
|
|
|
@ -1,44 +0,0 @@
|
|||
# encoding: utf-8
|
||||
require 'active_model/dirty'
|
||||
|
||||
module CouchRest #:nodoc:
|
||||
module Model #:nodoc:
|
||||
|
||||
# Dirty Tracking support via ActiveModel
|
||||
# mixin methods include:
|
||||
# #changed?, #changed, #changes, #previous_changes
|
||||
# #<attribute>_changed?, #<attribute>_change,
|
||||
# #reset_<attribute>!, #<attribute>_will_change!,
|
||||
# and #<attribute>_was
|
||||
#
|
||||
# Please see the specs or the documentation of
|
||||
# ActiveModel::Dirty for more information
|
||||
module Dirty
|
||||
extend ActiveSupport::Concern
|
||||
|
||||
included do
|
||||
include ActiveModel::Dirty
|
||||
after_save :clear_changed_attributes
|
||||
end
|
||||
|
||||
def initialize(*args)
|
||||
super
|
||||
@changed_attributes.clear if @changed_attributes
|
||||
end
|
||||
|
||||
def write_attribute(name, value)
|
||||
meth = :"#{name}_will_change!"
|
||||
__send__ meth if respond_to? meth
|
||||
super
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def clear_changed_attributes
|
||||
@previously_changed = changes
|
||||
@changed_attributes.clear
|
||||
true
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
|
@ -8,21 +8,21 @@ module CouchRest
|
|||
|
||||
module ClassMethods
|
||||
|
||||
# Load all documents that have the "couchrest-type" field equal to the
|
||||
# Load all documents that have the model_type_key's field equal to the
|
||||
# name of the current class. Take the standard set of
|
||||
# CouchRest::Database#view options.
|
||||
def all(opts = {}, &block)
|
||||
view(:all, opts, &block)
|
||||
end
|
||||
|
||||
# Returns the number of documents that have the "couchrest-type" field
|
||||
# Returns the number of documents that have the model_type_key's field
|
||||
# equal to the name of the current class. Takes the standard set of
|
||||
# CouchRest::Database#view options
|
||||
def count(opts = {}, &block)
|
||||
all({:raw => true, :limit => 0}.merge(opts), &block)['total_rows']
|
||||
end
|
||||
|
||||
# Load the first document that have the "couchrest-type" field equal to
|
||||
# Load the first document that have the model_type_key's field equal to
|
||||
# the name of the current class.
|
||||
#
|
||||
# ==== Returns
|
||||
|
|
|
@ -97,7 +97,7 @@ module CouchRest
|
|||
# ==== Returns
|
||||
# a document instance
|
||||
def create_from_database(doc = {})
|
||||
base = (doc['couchrest-type'].blank? || doc['couchrest-type'] == self.to_s) ? self : doc['couchrest-type'].constantize
|
||||
base = (doc[model_type_key].blank? || doc[model_type_key] == self.to_s) ? self : doc[model_type_key].constantize
|
||||
base.new(doc, :directly_set_attributes => true)
|
||||
end
|
||||
|
||||
|
|
|
@ -1,18 +1,13 @@
|
|||
# encoding: utf-8
|
||||
require 'set'
|
||||
module CouchRest
|
||||
module Model
|
||||
module Properties
|
||||
extend ActiveSupport::Concern
|
||||
|
||||
class IncludeError < StandardError; end
|
||||
|
||||
def self.included(base)
|
||||
base.class_eval <<-EOS, __FILE__, __LINE__ + 1
|
||||
extlib_inheritable_accessor(:properties) unless self.respond_to?(:properties)
|
||||
self.properties ||= []
|
||||
EOS
|
||||
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?(:[]=))
|
||||
included do
|
||||
extlib_inheritable_accessor(:properties) unless self.respond_to?(:properties)
|
||||
self.properties ||= []
|
||||
raise "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 (method_defined?(:[]) && method_defined?(:[]=))
|
||||
end
|
||||
|
||||
# Returns the Class properties
|
||||
|
@ -23,12 +18,45 @@ module CouchRest
|
|||
self.class.properties
|
||||
end
|
||||
|
||||
# Returns the Class properties with their values
|
||||
#
|
||||
# ==== Returns
|
||||
# Array:: the list of properties with their values
|
||||
def properties_with_values
|
||||
props = {}
|
||||
properties.each { |property| props[property.name] = read_attribute(property.name) }
|
||||
props
|
||||
end
|
||||
|
||||
# Read the casted value of an attribute defined with a property.
|
||||
#
|
||||
# ==== Returns
|
||||
# Object:: the casted attibutes value.
|
||||
def read_attribute(property)
|
||||
self[find_property!(property).to_s]
|
||||
end
|
||||
|
||||
# Store a casted value in the current instance of an attribute defined
|
||||
# with a property.
|
||||
def write_attribute(property, value)
|
||||
prop = find_property!(property)
|
||||
self[prop.to_s] = prop.is_a?(String) ? value : prop.cast(self, value)
|
||||
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
|
||||
|
||||
|
||||
private
|
||||
# The following methods should be accessable by the Model::Base Class, but not by anything else!
|
||||
def apply_all_property_defaults
|
||||
return if self.respond_to?(:new?) && (new? == false)
|
||||
# TODO: cache the default object
|
||||
|
@ -37,13 +65,54 @@ module CouchRest
|
|||
end
|
||||
end
|
||||
|
||||
private
|
||||
def prepare_all_attributes(doc = {}, options = {})
|
||||
apply_all_property_defaults
|
||||
if options[:directly_set_attributes]
|
||||
directly_set_read_only_attributes(doc)
|
||||
else
|
||||
doc = remove_protected_attributes(doc)
|
||||
end
|
||||
directly_set_attributes(doc) unless doc.nil?
|
||||
end
|
||||
|
||||
def find_property!(property)
|
||||
prop = property.is_a?(Property) ? property : self.class.properties.detect {|p| p.to_s == property.to_s}
|
||||
raise ArgumentError, "Missing property definition for #{property.to_s}" unless prop
|
||||
raise ArgumentError, "Missing property definition for #{property.to_s}" if prop.nil?
|
||||
prop
|
||||
end
|
||||
|
||||
# Set all the attributes and return a hash with the attributes
|
||||
# that have not been accepted.
|
||||
def directly_set_attributes(hash)
|
||||
hash.reject do |attribute_name, attribute_value|
|
||||
if self.respond_to?("#{attribute_name}=")
|
||||
self.send("#{attribute_name}=", attribute_value)
|
||||
true
|
||||
elsif mass_assign_any_attribute # config option
|
||||
self[attribute_name] = attribute_value
|
||||
true
|
||||
else
|
||||
false
|
||||
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
|
||||
|
||||
|
||||
module ClassMethods
|
||||
|
||||
def property(name, *options, &block)
|
||||
|
@ -91,7 +160,8 @@ module CouchRest
|
|||
type = [type] # inject as an array
|
||||
end
|
||||
property = Property.new(name, type, options)
|
||||
create_property_alias(property) if property.alias
|
||||
create_property_getter(property)
|
||||
create_property_setter(property) unless property.read_only == true
|
||||
if property.type_class.respond_to?(:validates_casted_model)
|
||||
validates_casted_model property.name
|
||||
end
|
||||
|
@ -99,15 +169,49 @@ module CouchRest
|
|||
property
|
||||
end
|
||||
|
||||
def create_property_alias(property)
|
||||
# defines the getter for the property (and optional aliases)
|
||||
def create_property_getter(property)
|
||||
# meth = property.name
|
||||
class_eval <<-EOS, __FILE__, __LINE__ + 1
|
||||
def #{property.alias.to_s}
|
||||
#{property.name}
|
||||
def #{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}?
|
||||
value = read_attribute('#{property.name}')
|
||||
!(value.nil? || value == false)
|
||||
end
|
||||
EOS
|
||||
end
|
||||
|
||||
if property.alias
|
||||
class_eval <<-EOS, __FILE__, __LINE__ + 1
|
||||
alias #{property.alias.to_sym} #{property.name.to_sym}
|
||||
EOS
|
||||
end
|
||||
end
|
||||
|
||||
# defines the setter for the property (and optional aliases)
|
||||
def create_property_setter(property)
|
||||
property_name = property.name
|
||||
class_eval <<-EOS
|
||||
def #{property_name}=(value)
|
||||
write_attribute('#{property_name}', value)
|
||||
end
|
||||
EOS
|
||||
|
||||
if property.alias
|
||||
class_eval <<-EOS
|
||||
alias #{property.alias.to_sym}= #{property_name.to_sym}=
|
||||
EOS
|
||||
end
|
||||
end
|
||||
|
||||
end # module ClassMethods
|
||||
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
|
@ -58,7 +58,8 @@ module CouchRest::Model
|
|||
if default.class == Proc
|
||||
default.call
|
||||
else
|
||||
Marshal.load(Marshal.dump(default))
|
||||
# Marshal.load(Marshal.dump(default)) # Removed as there are no failing tests and caused mutex errors
|
||||
default
|
||||
end
|
||||
end
|
||||
|
||||
|
|
|
@ -1,7 +1,9 @@
|
|||
module CouchRest
|
||||
module Model
|
||||
module AttributeProtection
|
||||
# Attribute protection from mass assignment to CouchRest::Model properties
|
||||
module PropertyProtection
|
||||
extend ActiveSupport::Concern
|
||||
|
||||
# Property protection from mass assignment to CouchRest::Model properties
|
||||
#
|
||||
# Protected methods will be removed from
|
||||
# * new
|
||||
|
@ -20,7 +22,7 @@ module CouchRest
|
|||
#
|
||||
# 3) Mix and match, and assume all unspecified properties are protected.
|
||||
# property :name, :accessible => true
|
||||
# property :admin, :protected => true
|
||||
# property :admin, :protected => true # ignored
|
||||
# property :phone # this will be automatically protected
|
||||
#
|
||||
# Note: the timestamps! method protectes the created_at and updated_at properties
|
||||
|
@ -32,11 +34,16 @@ module CouchRest
|
|||
|
||||
module ClassMethods
|
||||
def accessible_properties
|
||||
properties.select { |prop| prop.options[:accessible] }
|
||||
props = properties.select { |prop| prop.options[:accessible] }
|
||||
if props.empty?
|
||||
props = properties.select { |prop| !prop.options[:protected] }
|
||||
end
|
||||
props
|
||||
end
|
||||
|
||||
def protected_properties
|
||||
properties.select { |prop| prop.options[:protected] }
|
||||
accessibles = accessible_properties
|
||||
properties.reject { |prop| accessibles.include?(prop) }
|
||||
end
|
||||
end
|
||||
|
||||
|
@ -48,28 +55,17 @@ module CouchRest
|
|||
self.class.protected_properties
|
||||
end
|
||||
|
||||
# Return a new copy of the attributes hash with protected attributes
|
||||
# removed.
|
||||
def remove_protected_attributes(attributes)
|
||||
protected_names = properties_to_remove_from_mass_assignment.map { |prop| prop.name }
|
||||
return attributes if protected_names.empty?
|
||||
protected_names = protected_properties.map { |prop| prop.name }
|
||||
return attributes if protected_names.empty? or attributes.nil?
|
||||
|
||||
attributes.reject! do |property_name, property_value|
|
||||
attributes.reject do |property_name, property_value|
|
||||
protected_names.include?(property_name.to_s)
|
||||
end if attributes
|
||||
|
||||
attributes || {}
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def properties_to_remove_from_mass_assignment
|
||||
to_remove = protected_properties
|
||||
|
||||
unless accessible_properties.empty?
|
||||
to_remove += properties.reject { |prop| prop.options[:accessible] }
|
||||
end
|
||||
|
||||
to_remove
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
end
|
|
@ -79,7 +79,7 @@ module CouchRest
|
|||
# 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/
|
||||
if value.gsub(/,/, '.').gsub(/\.(?!\d*\Z)/, '').to_str =~ /\A(-?(?:0|[1-9]\d*)(?:\.\d+)?|(?:\.\d+))\z/
|
||||
$1.send(method)
|
||||
else
|
||||
value
|
||||
|
|
190
lib/couchrest/model/view.rb
Normal file
190
lib/couchrest/model/view.rb
Normal file
|
@ -0,0 +1,190 @@
|
|||
|
||||
#### NOTE Work in progress! Not yet used!
|
||||
|
||||
module CouchRest
|
||||
module Model
|
||||
|
||||
# A proxy class that allows view queries to be created using
|
||||
# chained method calls. After each call a new instance of the method
|
||||
# is created based on the original in a similar fashion to ruby's sequel
|
||||
# library, or Rails 3's Arel.
|
||||
#
|
||||
# CouchDB views have inherent limitations, so joins and filters as used in
|
||||
# a normal relational database are not possible. At least not yet!
|
||||
#
|
||||
#
|
||||
#
|
||||
class View
|
||||
|
||||
attr_accessor :query, :design, :database, :name
|
||||
|
||||
# Initialize a new View object. This method should not be called from outside CouchRest Model.
|
||||
def initialize(parent, new_query = {}, name = nil)
|
||||
if parent.is_a? Base
|
||||
raise "Name must be provided for view to be initialized" if name.nil?
|
||||
@name = name
|
||||
@database = parent.database
|
||||
@query = { :reduce => false }
|
||||
elsif parent.is_a? View
|
||||
@database = parent.database
|
||||
@query = parent.query.dup
|
||||
else
|
||||
raise "View cannot be initialized without a parent Model or View"
|
||||
end
|
||||
@query.update(new_query)
|
||||
super
|
||||
end
|
||||
|
||||
|
||||
# == View Execution Methods
|
||||
#
|
||||
# Send a request to the CouchDB database using the current query values.
|
||||
|
||||
# Inmediatly send a request to the database for all documents provided by the query.
|
||||
#
|
||||
def all(&block)
|
||||
args = include_docs.query
|
||||
|
||||
end
|
||||
|
||||
# Inmediatly send a request for the first result of the dataset. This will override
|
||||
# any limit set in the view previously.
|
||||
def first(&block)
|
||||
args = limit(1).include_docs.query
|
||||
|
||||
end
|
||||
|
||||
def info
|
||||
|
||||
end
|
||||
|
||||
def offset
|
||||
|
||||
end
|
||||
|
||||
def total_rows
|
||||
|
||||
end
|
||||
|
||||
def rows
|
||||
|
||||
end
|
||||
|
||||
|
||||
# == View Filter Methods
|
||||
#
|
||||
# View filters return an copy of the view instance with the query
|
||||
# modified appropriatly. Errors will be raised if the methods
|
||||
# are combined in an incorrect fashion.
|
||||
#
|
||||
|
||||
|
||||
# Find all entries in the index whose key matches the value provided.
|
||||
#
|
||||
# Cannot be used when the +#startkey+ or +#endkey+ have been set.
|
||||
def key(value)
|
||||
raise "View#key cannot be used when startkey or endkey have been set" unless query[:startkey].nil? && query[:endkey].nil?
|
||||
update_query(:key => value)
|
||||
end
|
||||
|
||||
# Find all index keys that start with the value provided. May or may not be used in
|
||||
# conjunction with the +endkey+ option.
|
||||
#
|
||||
# When the +#descending+ option is used (not the default), the start and end keys should
|
||||
# be reversed.
|
||||
#
|
||||
# Cannot be used if the key has been set.
|
||||
def startkey(value)
|
||||
raise "View#startkey cannot be used when key has been set" unless query[:key].nil?
|
||||
update_query(:startkey => value)
|
||||
end
|
||||
|
||||
# The result set should start from the position of the provided document.
|
||||
# The value may be provided as an object that responds to the +#id+ call
|
||||
# or a string.
|
||||
def startkey_doc(value)
|
||||
update_query(:startkey_docid => value.is_a?(String) ? value : value.id
|
||||
end
|
||||
|
||||
# The opposite of +#startkey+, finds all index entries whose key is before the value specified.
|
||||
#
|
||||
# See the +#startkey+ method for more details and the +#inclusive_end+ option.
|
||||
def endkey(value)
|
||||
raise "View#endkey cannot be used when key has been set" unless query[:key].nil?
|
||||
update_query(:endkey => value)
|
||||
end
|
||||
|
||||
# The result set should end at the position of the provided document.
|
||||
# The value may be provided as an object that responds to the +#id+ call
|
||||
# or a string.
|
||||
def endkey_doc(value)
|
||||
update_query(:endkey_docid => value.is_a?(String) ? value : value.id
|
||||
end
|
||||
|
||||
|
||||
# The results should be provided in descending order.
|
||||
#
|
||||
# Descending is false by default, this method will enable it and cannot be undone.
|
||||
def descending
|
||||
update_query(:descending => true)
|
||||
end
|
||||
|
||||
# Limit the result set to the value supplied.
|
||||
def limit(value)
|
||||
update_query(:limit => value)
|
||||
end
|
||||
|
||||
# Skip the number of entries in the index specified by value. This would be
|
||||
# the equivilent of an offset in SQL.
|
||||
#
|
||||
# The CouchDB documentation states that the skip option should not be used
|
||||
# with large data sets as it is inefficient. Use the +startkey_doc+ method
|
||||
# instead to skip ranges efficiently.
|
||||
def skip(value = 0)
|
||||
update_query(:skip => value)
|
||||
end
|
||||
|
||||
# Use the reduce function on the view. If none is available this method will fail.
|
||||
def reduce
|
||||
update_query(:reduce => true)
|
||||
end
|
||||
|
||||
# Control whether the reduce function reduces to a set of distinct keys or to a single
|
||||
# result row.
|
||||
#
|
||||
# By default the value is false, and can only be set when the view's +#reduce+ option
|
||||
# has been set.
|
||||
def group
|
||||
raise "View#reduce must have been set before grouping is permitted" unless query[:reduce]
|
||||
update_query(:group => true)
|
||||
end
|
||||
|
||||
def group_level(value)
|
||||
raise "View#reduce and View#group must have been set before group_level is called" unless query[:reduce] && query[:group]
|
||||
update_query(:group_level => value.to_i)
|
||||
end
|
||||
|
||||
|
||||
protected
|
||||
|
||||
def update_query(new_query = {})
|
||||
self.class.new(self, new_query)
|
||||
end
|
||||
|
||||
# Used internally to ensure that docs are provided. Should not be used outside of
|
||||
# the view class under normal circumstances.
|
||||
def include_docs
|
||||
raise "Documents cannot be returned from a view that is prepared for a reduce" if query[:reduce]
|
||||
update_query(:include_docs => true)
|
||||
end
|
||||
|
||||
|
||||
def execute(&block)
|
||||
|
||||
|
||||
end
|
||||
|
||||
|
||||
end
|
||||
end
|
||||
end
|
|
@ -23,7 +23,7 @@ module CouchRest
|
|||
# view_by :tags,
|
||||
# :map =>
|
||||
# "function(doc) {
|
||||
# if (doc['couchrest-type'] == 'Post' && doc.tags) {
|
||||
# if (doc['model'] == 'Post' && doc.tags) {
|
||||
# doc.tags.forEach(function(tag){
|
||||
# emit(doc.tag, 1);
|
||||
# });
|
||||
|
@ -39,7 +39,7 @@ module CouchRest
|
|||
# function:
|
||||
#
|
||||
# function(doc) {
|
||||
# if (doc['couchrest-type'] == 'Post' && doc.date) {
|
||||
# if (doc['model'] == 'Post' && doc.date) {
|
||||
# emit(doc.date, null);
|
||||
# }
|
||||
# }
|
||||
|
@ -77,7 +77,7 @@ module CouchRest
|
|||
ducktype = opts.delete(:ducktype)
|
||||
unless ducktype || opts[:map]
|
||||
opts[:guards] ||= []
|
||||
opts[:guards].push "(doc['couchrest-type'] == '#{self.to_s}')"
|
||||
opts[:guards].push "(doc['#{model_type_key}'] == '#{self.to_s}')"
|
||||
end
|
||||
keys.push opts
|
||||
design_doc.view_by(*keys)
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue