Permalink
Browse files

Allowing an attribute and its validations to be set at the same time

  • Loading branch information...
1 parent 0cc4f54 commit bcc37a1fef7ce281feb28e8ad55bf27d86a4c7a3 @ajn ajn committed Aug 4, 2011
View
@@ -7,5 +7,6 @@
module ModestModel
autoload :Base, File.expand_path('../modest_model/base', __FILE__)
autoload :Validators, File.expand_path('../modest_model/validators', __FILE__)
+ autoload :CombinedAttr, File.expand_path('../modest_model/combined_attr', __FILE__)
autoload :Resource, File.expand_path('../modest_model/resource', __FILE__)
end
@@ -8,6 +8,7 @@ class Base
include ActiveModel::AttributeMethods
include ModestModel::Validators
+ extend ModestModel::CombinedAttr
def initialize(attributes = {}, options={})
self.assign_attributes(attributes, options)
@@ -0,0 +1,10 @@
+module ModestModel
+ module CombinedAttr
+ def attribute *attrs
+ options = attrs.extract_options!
+ validations = options.slice!(*_validates_default_keys)
+ attributes *attrs
+ validates *(attrs +[validations]) if validations.any?
+ end
+ end
+end
@@ -1,5 +1,4 @@
class SampleModel < ModestModel::Base
attributes :name, :email
- attributes :nickname
- validates :nickname, :absence => true
+ attribute :nickname, :absence => true
end
@@ -1,9 +1,11 @@
class SampleResource < ModestModel::Resource
- attributes :id, :name, :email, :number
- attributes :nickname, :saved_at, :destroyed_at
+ attributes :id, :name, :email
+ attributes :saved_at, :destroyed_at
attributes :find_callback, :create_callback, :save_callback, :update_callback, :destroy_callback
- validates :nickname, :absence => true
- validates :number, :numericality => {:allow_blank => true}
+
+ # Attributes with validations
+ attribute :nickname, :absence => true
+ attribute :number, :numericality => {:allow_blank => true}
after_find :set_find_callback
def set_find_callback

0 comments on commit bcc37a1

Please sign in to comment.