Class: ActiveOopish::Validator
- Inherits:
-
Object
- Object
- ActiveOopish::Validator
- Defined in:
- lib/activeoopish/validator.rb
Overview
Public: Base class for validators.
Example
class BookValidator < ActiveOopish::Validator
declear do
validates :author, presence: true
validate :title_must_include_author_name, if: :biography?
end
private
def (book)
unless book.title.include?(book..name)
book.errors.add(:author, "cannot write a biography for other people")
end
end
def biography?(book)
book.category == :biography
end
end
class Book < ActiveRecord::Base
belongs_to :author, class_name: 'User'
BookValidator.monitor(self)
end
BookValidator.monitor?(Book)
# => true
book = Book.new(title: 'Qiitan biography', author: User.new(name: 'Yaotti'))
book.valid?
# => false
book.errors.(:author).first
# => "author cannot write a biography of another person"
Defined Under Namespace
Classes: AlreadyMonitored, DeclarationNotFound, Error
Class Method Summary collapse
-
.injection_name ⇒ Object
Internal: Its name.
- .inspect ⇒ Object
-
.monitor(model_class) ⇒ Object
Public: Start validating the given model_class’s instances.
-
.monitoring?(target) ⇒ Boolean
Public: Whether the given model_class is watched by it.
Class Method Details
.injection_name ⇒ Object
Internal: Its name.
Returns a Symbol.
86 87 88 |
# File 'lib/activeoopish/validator.rb', line 86 def injection_name @method_name ||= "__validator_#{name.downcase.gsub('::', '_')}" end |
.inspect ⇒ Object
90 91 92 |
# File 'lib/activeoopish/validator.rb', line 90 def inspect name end |
.monitor(model_class) ⇒ Object
Public: Start validating the given model_class’s instances.
model_class - A model Class to be validated by it.
Raises AlreadyMonitored if the given model_class has already been
monitored.
Raises DeclarationNotFound when it has not decleared yet. Returns nothing.
66 67 68 69 70 71 |
# File 'lib/activeoopish/validator.rb', line 66 def monitor(model_class) fail AlreadyMonitored if monitoring?(model_class) define_accessor_to_model_class(model_class) apply_decleared_rules_to_model_class(model_class) monitoring_model_classes << model_class end |
.monitoring?(target) ⇒ Boolean
Public: Whether the given model_class is watched by it.
target - A class which includes ActiveModel::Validations or its instance.
Returns true or false.
78 79 80 81 |
# File 'lib/activeoopish/validator.rb', line 78 def monitoring?(target) model_class = target.is_a?(ActiveModel::Validations) ? target.class : target monitoring_model_classes.include?(model_class) end |