Ruby中的动态验证和元编程
我正在尝试开发一个应用程序,该应用程序可以向不同的用户提供相同的资源,并且资源可能具有基于用户的不同验证行为。
我试图使用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
它的唯一目的是添加一个方法,根据给定的参数添加条件验证。
它在使用一个为true的参数调用时会添加验证,但它不会干净地执行。它似乎没有像我想象的那样分离子类。
它可以通过以下测试来说明:
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
再次添加验证...
为什么我无法将验证添加到特定的配置文件后代?
我使用的是Ruby 1.9.2和Rails 3.06。请理解我想了解如何使这个动态类创建工作 - 我知道“标准”自定义验证。
没有找到相关结果
已邀请:
2 个回复
惭法搽
粱委教