Class: DataMapper::ContextualValidations
- Inherits:
-
Object
- Object
- DataMapper::ContextualValidations
- Defined in:
- lib/data_mapper/validations/contextual_validations.rb
Defined Under Namespace
Classes: UnknownContextError
Constant Summary collapse
- DEFAULT_CONTEXTS =
Add your custom contexts here.
[ :general, :create, :save, :update ]
Instance Method Summary collapse
-
#clear! ⇒ Object
Clear out all the currently defined validators.
-
#context(name) ⇒ Object
Retrieves a context by symbol.
-
#execute(context_name, target) ⇒ Object
Execute all validations against an instance for a specified context, including the “always-on” :general context.
-
#initialize ⇒ ContextualValidations
constructor
A new instance of ContextualValidations.
Constructor Details
#initialize ⇒ ContextualValidations
Returns a new instance of ContextualValidations.
15 16 17 |
# File 'lib/data_mapper/validations/contextual_validations.rb', line 15 def initialize @contexts = Hash.new { |h,k| h[k.to_sym] = [] } end |
Instance Method Details
#clear! ⇒ Object
Clear out all the currently defined validators. This makes testing easier.
31 32 33 |
# File 'lib/data_mapper/validations/contextual_validations.rb', line 31 def clear! @contexts.clear end |
#context(name) ⇒ Object
Retrieves a context by symbol. Raises an exception if the symbol isn’t a member of DEFAULT_CONTEXTS. This isn’t to keep you from adding your own contexts, it’s just to prevent errors due to typos. When adding your own contexts just remember to add it to DEFAULT_CONTEXTS first.
24 25 26 27 |
# File 'lib/data_mapper/validations/contextual_validations.rb', line 24 def context(name) raise UnknownContextError.new(name) unless DEFAULT_CONTEXTS.include?(name) @contexts[name] end |
#execute(context_name, target) ⇒ Object
Execute all validations against an instance for a specified context, including the “always-on” :general context.
37 38 39 40 41 42 43 44 45 46 |
# File 'lib/data_mapper/validations/contextual_validations.rb', line 37 def execute(context_name, target) target.errors.clear! validations = context(context_name) validations += context(:general) unless context_name == :general validations.inject(true) do |result, validator| result & validator.call(target) end end |