0

我有一个包含 ActiveModel::Model 模块的表单类,以便进行基本验证

class RegistrationForm
  include ActiveModel::Model
  ...
  validates_presence_of ....
end

我想添加一些额外的类验证方法,如下所示

class RegistrationForm
  include ActiveModel::Model
  ...
  my_custom_class_validation_method
end

我希望在包含 ActiveModel::Model 模块时自动包含此方法。

我尝试使用像这里这样的解决方案:将类方法添加到 ActiveRecord::Base 但没有运气。

这可能吗?

4

3 回答 3

1

好的。再来一个片段。我不确定,但是这个怎么样?

# This should be locate in lib/your_custom_validator.rb
class YourCustomValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    # validation login is here
  end
end

I think, now you can use that validator in any model. 


# You can use that validator like this. 
class RegistrationForm < ActiveRecord::Base
  validates :some_column_name, your_custom_validator: true
end

干杯,桑吉尔。

于 2013-10-04T22:54:51.337 回答
0

Yet another approach - I build new module that includes ActiveModel::Model in itself and is extended with new validation method.

module ExtendedModel
  module ClassMethods
    def my_custom_validation_method(*args)
      # define validation here
    end
  end

  def self.included(base)
    base.class_eval do
      include ActiveModel::Model
      extend ClassMethods
    end
  end
end

Then I included this new module in my form class

class RegistrationForm
  include ExtendedModel

  my_custom_validation_method
  ...
end

Of course this solution is not 100% elegant:

  1. it requires that all my extensions must be added to ExtendedModel module.
  2. models that inherit from ActiveRecord::Base must be supplied with these extra methods separately
于 2013-10-07T07:31:39.597 回答
0

这个代码片段可能是一个好的开始。

module ActiveModel
  module Model
    def self.included(base)
      base.extend(ClassMethods)
      base.class_eval %{
            class << self
              def your_custom_validator
              end
            end  
          }
    end
  end
end
于 2013-10-04T22:02:02.460 回答