是否可以为每个实例使用Rails ActiveModel :: Validations?

时间:2011-10-18 13:13:43

标签: ruby-on-rails validation configuration

我的代码摘录:

module Configuracao
  extend self

  class Key
    include ActiveModel::Validations
    attr_accessor :name, :type, :default, :validations, :group, :available_values

    def initialize(params)
      params.symbolize_keys!.assert_valid_keys(:name, :type, :default, :validations, :group, :available_values)
      @group = params[:group]
      @name = params[:name]
      @type = params[:type]
      @available_values = params[:available_values]
      @default = params[:default]
      @validations = params[:validations]

      #in this way each validation is being added for all keys
      Configuracao::Key.class_eval do
        validates :value, params[:validations]
      end
    end
  end
end

因此,对于每个实例密钥,我将在散列中传递不同的验证,例如:

Key.new( validations: { presence: true, numericality: true } )
Key.new( validations: { length: { maximum: 30 } } )

有办法吗?

2 个答案:

答案 0 :(得分:2)

我找到了一个解决方案,可能不是那么优雅或最好的方法,但它有效

def initialize(params)
  params.symbolize_keys!.assert_valid_keys(:name, :type, :default, :validations, :group, :available_values)
  @group = params[:group]
  @name = params[:name]
  @type = params[:type]
  @available_values = params[:available_values]
  @default = params[:default]
  @@current_validations = nil
  @@current_validations = @validations = params[:validations]

  class << self
    validates :value, @@current_validations unless @@current_validations.blank?
  end
end

现在每次我实例化一个 Key 时,只会为该实例修改该类

答案 1 :(得分:-1)

这会有用吗?

...
validates :all_hash_validations_pass
...

def all_hash_validations_pass
  ...iterate through the hash here, and validate each of them
end

如果没有,您应该可以使用custom validator进行更多控制。