【发布时间】:2011-08-02 15:39:42
【问题描述】:
我正在尝试开发一个应用程序,该应用程序可以将相同的资源呈现给不同的用户,并且该资源可能具有基于用户的不同验证行为。
我曾尝试使用 Ruby 元编程以一种简单的方式解决此问题,但我似乎遗漏了这方面的一些关键知识。
我可以用一个模型来举例说明
class Profile < ActiveRecord::Base
# validates_presence_of :string1
end
模型有一个属性“string1”,有时需要,有时不需要。我想为每个用户创建子类(原因在此简化中不明显)并创建了一个我想包含的模块:
module ExtendProfile
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def configure_validation(required)
if required
class_eval("ActiveRecord::Base.validates_presence_of :string1")
end
end
end
end
它的唯一目的是添加一个基于给定参数添加条件验证的方法。
当使用一个真实的参数调用它时,它确实添加了验证,但它并没有完全做到这一点。看来它并没有像我想象的那样分离子类。
可以通过以下测试来说明:
profile = Profile.new
profile.save; profile.errors
=> []
默认情况下可以保存配置文件而不会出错。
Object::const_set('FirstExtendedProfile'.intern, Class::new(Profile) { include ExtendProfile })
FirstExtendedProfile.configure_validation(true)
fep = FirstExtendedProfile.new; fep.save; fep.errors
=> {:string1=>["skal udfyldes", "skal udfyldes"]}
创建一个新的子类并调用 configuring_validation 会添加验证,但由于某种原因,它在验证期间被调用了两次(“skal udfyldes” - 是丹麦语,表示它是必需的)。
Object::const_set('SecondExtendedProfile'.intern, Class::new(Profile) { include ExtendProfile })
sep = SecondExtendedProfile.new; sep.save; sep.errors
=> {:string1=>["skal udfyldes"]}
创建了另一个后代,即使 configure_validation 未被调用,它仍会验证 string1 属性(但现在只有一次)。
添加另一个后代并调用 configure_validation 再次添加验证...
为什么我无法将验证添加到特定的 Profile 后代?
我正在使用 Ruby 1.9.2 和 Rails 3.06。请理解,我想了解如何使这个动态类创建工作 - 我知道“标准”自定义验证。
【问题讨论】:
-
目前还不确定,但可能是因为验证器列表保存在类中的类变量中,该类变量是
ActiveRecord::base的直接后代,并且该变量在其后代之间共享。是这样吗?
标签: ruby-on-rails ruby validation dynamic metaprogramming