Skip to content

Commit

Permalink
Adding before/after validation callbacks
Browse files Browse the repository at this point in the history
  • Loading branch information
durran committed Nov 8, 2009
1 parent bb6f3fc commit c77a602
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 2 deletions.
1 change: 1 addition & 0 deletions lib/mongoid/commands.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
require "mongoid/commands/destroy"
require "mongoid/commands/destroy_all"
require "mongoid/commands/save"
require "mongoid/commands/validate"

module Mongoid #:nodoc:

Expand Down
2 changes: 1 addition & 1 deletion lib/mongoid/commands/save.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ class Save
#
# Returns: +Document+ if validation passes, +false+ if not.
def self.execute(doc)
return false unless doc.valid?
return false unless Validate.execute(doc)
doc.run_callbacks :before_save
parent = doc.parent
parent ? Save.execute(parent) : doc.collection.save(doc.attributes)
Expand Down
20 changes: 20 additions & 0 deletions lib/mongoid/commands/validate.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
module Mongoid #:nodoc:
module Commands
class Validate
# Performs validation of the supplied +Document+, handling all associated
# callbacks.
#
# Options:
#
# doc: A +Document+ that is going to be persisted.
#
# Returns: +true+ if validation passes, +false+ if not.
def self.execute(doc)
doc.run_callbacks(:before_validation)
validated = doc.valid?
doc.run_callbacks(:after_validation)
return validated
end
end
end
end
4 changes: 3 additions & 1 deletion lib/mongoid/document.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,12 @@ class Document
:after_destroy,
:after_save,
:after_update,
:after_validation,
:before_create,
:before_destroy,
:before_save,
:before_update
:before_update,
:before_validation

class << self

Expand Down
25 changes: 25 additions & 0 deletions spec/unit/mongoid/commands/validate_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
require File.expand_path(File.join(File.dirname(__FILE__), "/../../../spec_helper.rb"))

describe Mongoid::Commands::Validate do

describe "#execute" do

before do
@document = stub(:run_callbacks)
end

it "validates the document" do
@document.expects(:valid?).returns(true)
Mongoid::Commands::Validate.execute(@document).should be_true
end

it "runs the before and after validate callbacks" do
@document.expects(:valid?).returns(true)
@document.expects(:run_callbacks).with(:before_validation)
@document.expects(:run_callbacks).with(:after_validation)
Mongoid::Commands::Validate.execute(@document)
end

end

end

0 comments on commit c77a602

Please sign in to comment.