我正在为我公司编写的软件开发一个测试框架。我们的产品是基于网络的,在运行 RESTful 请求后,我想处理结果。我希望能够在每个命令类中进行 activerecord 类型验证,以便在运行后,结果会自动针对所有“验证”进行测试。但是,我不知道该怎么做。我的代码如下所示(简化以显示重要部分)。
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中的验证一样。有人能告诉我该怎么做吗?谢谢
没有过多查看您的代码,以下是我对实现验证类方法的看法:
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 => /^[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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)