![](/img/trans.png)
[英]When using class_eval in ruby, how to access the constant in the original class?
[英]How do you pass self to class_eval in ruby?
我正在做一个元编程任务,在这里我试图使用一种方法在调用类中定义多态关联,同时在目标类中定义关联。 我需要传递调用类的名称来获得正确的关联。 这是一个片段,应该可以使您理解:
class SomeClass < ActiveRecord::Base
has_many :join_models, :dependent=>:destroy
end
class JoinModel < ActiveRecord::Base
belongs_to :some_class
belongs_to :entity, :polymorphic=>true
end
module Foo
module ClassMethods
def acts_as_entity
has_many :join_models, :as=>:entity, :dependent=>:destroy
has_many :some_classes, :through=>:join_models
klass = self.name.tableize
SomeClass.class_eval "has_many :#{klass}, :through=>:join_models"
end
end
end
我想消除klass=
行,但不知道如何class_eval
self
的引用从调用类传递给class_eval
。
有什么建议么?
字符串参数将在当前上下文中解释,因此您可以在其中自由调用self.name
或直接name
:
SomeClass.class_eval "has_many :#{name.tableize}, :through=>:join_models"
如果不是使用块而是对字符串进行评估,请注意class_exec
是class_eval
的变体,它允许您自然地传递参数。 所以:
SomeClass.class_exec(name.tableize.to_sym) do |klass|
has_many klass, :through=>:join_models
end
它是1.8.7的新功能,因此如果在1.8.6中,则require 'backports/1.8.7'
。
注意:我假设您完全需要评估,因为在您的特定示例中,您可以直接调用该方法,不是吗?
SomeClass.has_many name.tableize.to_sym, :through=>:join_models
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.