如何在activerecord之外创建activerecord样式validation?

我正在研究我公司编写的软件的测试框架。 我们的产品是基于Web的,在运行RESTful请求后,我想处理结果。 我希望能够在每个命令类中使用activerecord类型validation,以便在运行后,结果会自动针对所有“validation”进行测试。 但是,我不知道该怎么做。 我的代码看起来像这样(简化显示重要部分)。

class CodesecureCommand def execute result = RestClient.post("http://#{codesecure.host_name_port}#{path}", post_data) return parse(result) #parse simple returns a Hpricot document end end class RunScan < CodesecureCommand #What I have now #I have to override the execute function so that it calls the local success method #to see if it failed or not. def execute() result = super() if success(result) return true else end end def success(result) result.search('div.transaction-message') do |message| if message.innerHTML.scan(/Configure abuse setting for domain users successfully\./).length == 1 return true end end end #What I would like is to be able to call execute (without having to override it). #then after it runs it calls back to this class to check #if the regex matches the command was successful and returns true test_success /regex/ #if test_success fails then these are called #the idea being that I can use the regex to identify errors that happened then #report them to the user identify_error /regex/, "message" identify_error /regex/, "message" end end 

我想要的是,在调用execute方法之后,test_success和identify_error会像activerecord中的validation一样被自动调用。 谁能告诉我怎么做? 谢谢

如果不仔细看你的代码,这是我对实现validation类方法的看法:

 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 

它假设ActiveSupport在Rails环境中。 你可能想要扩展它以允许每个属性有多个错误,使用instance.errors[attribute] << "the message" ,但我遗漏了这样的晦涩难懂,以保持这个简短的样本尽可能简单。

这是一个简短的用法示例:

 class MyClass include Validations attr_accessor :foo validates_presence_of :foo validates_format_of :foo, :with => /^[az]+$/ end a = MyClass.new puts a.valid? # => false a.foo = "letters" puts a.valid? # => true a.foo = "Oh crap$(!)*#" puts a.valid? # => false 

你想要Validatable : sudo gem install validatable validatable

 class Person include Validatable validates_presence_of :name attr_accessor :name end 

此外,Validatable不依赖于ActiveSupport。