我试图在 Rails 模式下干掉一些代码。
我有 4 个验证器,我试图通过使用 define_method 来干掉它们,但它不能正常工作。您可以在下面看到我的尝试以及下面的原始方法。充其量我没有得到验证,最坏的情况是我得到:
未定义的局部变量或方法“validate_weight”
class Product < ActiveRecord::Base
PRODUCT_DIMENSION_FIELDS = [:weight, :height, :width, :depth]
....
PRODUCT_DIMENSION_FIELDS.each do |meth|
#define_method('validate_' + meth.to_s) do
# errors.add(meth, "can't be blank") if has_parents? && meth.empty?
#end
#define_singleton_method('validate_' + meth.to_s) do
# errors.add(meth, "can't be blank") if has_parents? && meth.empty?
#end
#self.class.send(:define_method, ('validate_' + meth.to_s).to_sym) do
# errors.add(meth, "can't be blank") if has_parents? && meth.empty?
#end
end
# attempting to dry up these methods
def validate_weight
errors.add(:weight , "can't be blank") if has_parents? && weight.empty?
end
def validate_height
errors.add(:height , "can't be blank") if has_parents? && height.empty?
end
def validate_width
errors.add(:width , "can't be blank") if has_parents? && width.empty?
end
def validate_depth
errors.add(:depth , "can't be blank") if has_parents? && depth.empty?
end
end
有没有人有任何想法?