从另一个自定义验证中调用验证

Calling a validation from within another custom validation

我想要两个不同的自定义验证器,但希望其中一个验证器引用另一个:

class URLFormatValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    # ... validates the format of a URL is correct
  end    
end

class URLReachableValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    # ... validates the URL is reachable
  end    
end

如何在 URLReachableValidator 中引用 URLFormatValidator

class URLReachableValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    format_validator = URLFormatValidator.new
    format_validator.validate_each(record, attribute, value)
  end    
end

但我只想使用继承或混合来共享功能。

class URLValidator < ActiveModel::EachValidator
  # shared funtionality ...
end

class URLFormatValidator < URLValidator 
  def validate_each(record, attribute, value)
    # ...
  end    
end

class URLReachableValidator < URLValidator 
  def validate_each(record, attribute, value)
    # ...
  end    
end