I am working on a testing framework for the software that my company writes. Our product is web based and After I run a RESTful request I want to process the results. I want t
Without having looked much at your code, here's my take on implementing validation class methods:
module Validations
def self.included(base)
base.extend ClassMethods
end
def validate
errors.clear
self.class.validations.each {|validation| validation.call(self) }
end
def valid?
validate
errors.blank?
end
def errors
@errors ||= {}
end
module ClassMethods
def validations
@validations ||= []
end
def validates_presence_of(*attributes)
validates_attributes(*attributes) do |instance, attribute, value, options|
instance.errors[attribute] = "cant't be blank" if value.blank?
end
end
def validates_format_of(*attributes)
validates_attributes(*attributes) do |instance, attribute, value, options|
instance.errors[attribute] = "is invalid" unless value =~ options[:with]
end
end
def validates_attributes(*attributes, &proc)
options = attributes.extract_options!
validations << Proc.new { |instance|
attributes.each {|attribute|
proc.call(instance, attribute, instance.__send__(attribute), options)
}
}
end
end
end
It assumes that ActiveSupport is around, which it is in a Rails environment. You might want to extend it to allow multiple errors per attribute, with instance.errors[attribute] << "the message"
, but I left out obscurities like that in order to keep this short sample as simple as possible.
Here's a short usage example:
class MyClass
include Validations
attr_accessor :foo
validates_presence_of :foo
validates_format_of :foo, :with => /^[a-z]+$/
end
a = MyClass.new
puts a.valid?
# => false
a.foo = "letters"
puts a.valid?
# => true
a.foo = "Oh crap$(!)*#"
puts a.valid?
# => false
You want Validatable: sudo gem install validatable
class Person
include Validatable
validates_presence_of :name
attr_accessor :name
end
Also, Validatable does not have a dependency on ActiveSupport.