Skip to content

Commit

Permalink
Move validation code into the Validation plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
bkeepers committed May 25, 2011
1 parent fc3586f commit 48284d8
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 17 deletions.
5 changes: 0 additions & 5 deletions lib/mongo_mapper/plugins/callbacks.rb
Expand Up @@ -5,11 +5,6 @@ module Callbacks
extend ActiveSupport::Concern

module InstanceMethods
def valid?(context = nil)
context ||= (new_record? ? :create : :update)
super(context) && errors.empty?
end

def destroy
run_callbacks(:destroy) { super }
end
Expand Down
10 changes: 0 additions & 10 deletions lib/mongo_mapper/plugins/embedded_callbacks.rb
Expand Up @@ -6,7 +6,6 @@ module EmbeddedCallbacks

included do
extend ::ActiveModel::Callbacks
include ::ActiveModel::Validations::Callbacks

define_model_callbacks :save, :create, :update, :destroy, :only => [:before, :after]
end
Expand All @@ -32,12 +31,3 @@ def run_callbacks(callback, &block)
end
end
end

# Need to monkey patch ActiveModel for now since it uses the internal
# _run_validation_callbacks, which is impossible to override due to the
# way ActiveSupport::Callbacks is implemented.
ActiveModel::Validations::Callbacks.class_eval do
def run_validations!
run_callbacks(:validation) { super }
end
end
3 changes: 1 addition & 2 deletions lib/mongo_mapper/plugins/querying.rb
Expand Up @@ -140,8 +140,7 @@ def update_multiple(docs)
module InstanceMethods
def save(options={})
options.assert_valid_keys(:validate, :safe)
options.reverse_merge!(:validate => true)
!options[:validate] || valid? ? create_or_update(options) : false
create_or_update(options)
end

def save!(options={})
Expand Down
22 changes: 22 additions & 0 deletions lib/mongo_mapper/plugins/validations.rb
Expand Up @@ -5,6 +5,7 @@ module Validations
extend ActiveSupport::Concern

include ::ActiveModel::Validations
include ::ActiveModel::Validations::Callbacks

module ClassMethods
def validates_uniqueness_of(*attr_names)
Expand All @@ -16,6 +17,18 @@ def validates_associated(*attr_names)
end
end

module InstanceMethods
def save(options = {})
options.reverse_merge!(:validate => true)
!options[:validate] || valid? ? super : false
end

def valid?(context = nil)
context ||= (new_record? ? :create : :update)
super(context)
end
end

class UniquenessValidator < ::ActiveModel::EachValidator
def initialize(options)
super(options.reverse_merge(:case_sensitive => true))
Expand Down Expand Up @@ -64,3 +77,12 @@ def validate_each(record, attribute, value)
end
end
end

# Need to monkey patch ActiveModel for now since it uses the internal
# _run_validation_callbacks, which is impossible to override due to the
# way ActiveSupport::Callbacks is implemented.
ActiveModel::Validations::Callbacks.class_eval do
def run_validations!
run_callbacks(:validation) { super }
end
end

0 comments on commit 48284d8

Please sign in to comment.