class Bluepine::Validators::Proxy
Proxy
will act as a wrapper for a pair of attribute and value. It internally creates anonymous model with single attribute. This will simplify validation process for nested attributes (let's Visitor handles traversal instead).
@example
attribute = StringAttribute.new(:username) value = "john" proxy = Proxy.new(attribute, value) proxy.username # => "john" proxy.valid? # => true|false proxy.errors
Attributes
validators[R]
value[R]
Public Class Methods
model_name()
click to toggle source
rails requires this for anonymous model
# File lib/bluepine/validators/proxy.rb, line 23 def self.model_name ActiveModel::Name.new(self, nil, name) end
new(attribute, value = nil, options = {})
click to toggle source
# File lib/bluepine/validators/proxy.rb, line 27 def initialize(attribute, value = nil, options = {}) @attribute = attribute @value = attribute.value(value) @params = { attribute.name.to_sym => @value } @context = options[:context] || {} end
Public Instance Methods
messages()
click to toggle source
# File lib/bluepine/validators/proxy.rb, line 56 def messages errors.messages.values.flatten end
register(validators)
click to toggle source
Register validators to model
register(presense: true, ..., validators: [Validator1, Validator2, ...])
# File lib/bluepine/validators/proxy.rb, line 46 def register(validators) customs = validators.delete(:validators) || [] # register custom validators (requires :attributes) self.class.validates_with(*customs, attributes: [@attribute.name]) if customs.any? # register ActiveModel's validations e.g. presence: true self.class.validates(@attribute.name, validators) if validators.any? end
valid?()
click to toggle source
Calls superclass method
# File lib/bluepine/validators/proxy.rb, line 34 def valid? # clear validators self.class.clear_validators! register(@attribute.validators.dup) super end
Private Instance Methods
method_missing(m, *args, &block)
click to toggle source
Delegates method call to hash accessor e.g. `a.name` will become `a` and return `nil` for all undefined attributes e.g. `a.non_exists` => `nil`
# File lib/bluepine/validators/proxy.rb, line 64 def method_missing(m, *args, &block) normalize_missing_value m end
normalize_missing_value(method)
click to toggle source
# File lib/bluepine/validators/proxy.rb, line 72 def normalize_missing_value(method) @params.key?(method) ? @value : @context[method] end
respond_to_missing?(method, *)
click to toggle source
Calls superclass method
# File lib/bluepine/validators/proxy.rb, line 68 def respond_to_missing?(method, *) @params.key?(method) || super end