class Va::Validator
Attributes
attributes[R]
errors[R]
Public Class Methods
new(args={})
click to toggle source
# File lib/va.rb, line 8 def initialize(args={}) @attributes ||= self.class.defaults.dup args.each do |k, v| key = k.to_sym if self.class.keys.include?(key) @attributes[key] = v elsif ! self.class.ignore_unauthorized_attributes? raise UnauthorizedAttribute.new(key, self) end end @errors = {} @valid = validate end
Private Class Methods
attribute(attr_name, options={})
click to toggle source
# File lib/va.rb, line 89 def self.attribute(attr_name, options={}) name = attr_name.to_sym self.keys << name default = options.fetch(:default) { NotSpecified } self.defaults[name] = default unless default == NotSpecified define_method "#{name}=" do |value| attributes[name] = value end define_method "#{name}" do attributes[name] end end
defaults()
click to toggle source
# File lib/va.rb, line 85 def self.defaults @defaults ||= {} end
keys()
click to toggle source
# File lib/va.rb, line 81 def self.keys @keys ||= [] end
validate(*attrs, &block)
click to toggle source
# File lib/va.rb, line 53 def self.validate(*attrs, &block) msg = if attrs.last.is_a? String attrs.pop end attrs.each do |attr| raise UnknownAttribute unless keys.include?(attr) end validations << [attrs, msg, block] end
validate_multiple(*attrs, &block)
click to toggle source
# File lib/va.rb, line 63 def self.validate_multiple(*attrs, &block) attrs.each do |attr| validate(attr, &block) end end
validate_not_nil(*attrs)
click to toggle source
# File lib/va.rb, line 75 def self.validate_not_nil(*attrs) validate_multiple(*attrs) do |attr| attr != nil end end
validate_present(*attrs)
click to toggle source
# File lib/va.rb, line 69 def self.validate_present(*attrs) validate_multiple(*attrs) do |attr| attr && attr != "" end end
validations()
click to toggle source
# File lib/va.rb, line 49 def self.validations @validations ||= [] end
Public Instance Methods
message(msg="", *attrs)
click to toggle source
# File lib/va.rb, line 32 def message(msg="", *attrs) raise __callee__.inspect end
valid?()
click to toggle source
# File lib/va.rb, line 36 def valid? @valid end
validate()
click to toggle source
# File lib/va.rb, line 22 def validate invalid_validations = self.class.validations.select { |attrs, msg, validation| is_invalid = !validation.call(*attrs.map { |attr| self.send(attr)}) key = attrs.count == 1 ? attrs.first : attrs errors[key] = msg || "is invalid" if is_invalid is_invalid } invalid_validations.empty? end