ruby-on-rails - 如何在 activerecord 之外创建 activerecord 样式验证?

标签 ruby-on-rails ruby activerecord

我正在为我公司编写的软件开发一个测试框架。我们的产品是基于网络的,在我运行 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

关于ruby-on-rails - 如何在 activerecord 之外创建 activerecord 样式验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/775976/

相关文章:

ruby-on-rails - 应该使用 Rspec Gem 返回字符串 :Class"in belong_to test 的 "undefined method ` Reflect_on_association'

ruby-on-rails - 如何避免reactjs中的key/id问题并使 Prop 从父级传递到子级?

ruby-on-rails - Date.new 的参数错误

javascript - 在 Rails 中,如何在 HTML 页面上将 javascript 显示为文本?

ruby - 每个对象的实例变量在 Ruby 中是唯一的吗?

ruby-on-rails - rails : Selecting unique label values with its ID

ruby - 使用 Class.new 时访问外部范围

Ruby 可重复使用的 map block

ruby-on-rails - 是否可以在与 SQL 表达式对应的 activerecord 中定义虚拟属性?

ruby-on-rails - 如何验证 has_many 关系没有改变