Created
November 25, 2010 04:50
-
-
Save xaviershay/714925 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module DataMapper | |
| module Model::Relationship | |
| # By default, when validating a model, any child models will not be | |
| # checked for validation. This means that the following situation can | |
| # occur: | |
| # | |
| # user = User.new(:author => Author.new) | |
| # user.valid? # => false | |
| # user.author.valid? # => false | |
| # | |
| # This monkey patch automatically adds a validation to all associations | |
| # so that both methods in the above example will return false. Validations | |
| # are only run on dirty models (which includes new models), since clean | |
| # ones are assumed to be valid. | |
| def has_with_validation(cardinality, property, *args) | |
| has_without_validation(cardinality, property, *args) | |
| case cardinality | |
| when 1 | |
| validates_with_block property do | |
| val = send(property) | |
| if val && val.dirty? && !val.valid? | |
| [false, "#{property.to_s.titleize} must be valid"] | |
| else | |
| true | |
| end | |
| end | |
| when n | |
| validates_with_block property do | |
| val = send(property) | |
| if val.map(&:valid?).all? | |
| true | |
| else | |
| [false, "#{property.to_s.titleize} must be valid"] | |
| end | |
| end | |
| end | |
| end | |
| alias_method_chain :has, :validation | |
| end | |
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module DataMapper | |
| module Resource | |
| # Wrap a transaction around the save, useful when multiple nested models | |
| # will be saved at the same time. | |
| def save_with_transaction(*args) | |
| ret = nil | |
| transaction do | |
| ret = save(*args) | |
| end | |
| ret | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment