简体   繁体   English

您如何将自己传递给红宝石中的class_eval?

[英]How do you pass self to class_eval in ruby?

I'm working on a metaprogramming task, where I'm trying to use a single method to define a polymorphic association in the calling class, while also defining the association in the target class. 我正在做一个元编程任务,在这里我试图使用一种方法在调用类中定义多态关联,同时在目标类中定义关联。 I need to pass in the name of the calling class to get the association right. 我需要传递调用类的名称来获得正确的关联。 Here's a snippet that should get the idea across: 这是一个片段,应该可以使您理解:


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

I'd like to eliminate the klass= line, but don't know how else to pass a reference to self from the calling class into class_eval . 我想消除klass=行,但不知道如何class_eval self的引用从调用类传递给class_eval

any suggestions? 有什么建议么?

The string parameters will be interpreted in the current context, so you're free to call self.name there, or name directly: 字符串参数将在当前上下文中解释,因此您可以在其中自由调用self.name或直接name

SomeClass.class_eval "has_many :#{name.tableize}, :through=>:join_models"

If instead of doing an eval on a string you were using a block, note that class_exec is a variation on class_eval that allows you to pass parameters naturally. 如果不是使用块而是对字符串进行评估,请注意class_execclass_eval的变体,它允许您自然地传递参数。 So: 所以:

SomeClass.class_exec(name.tableize.to_sym) do |klass|
  has_many klass, :through=>:join_models
end

It is new to 1.8.7, so you'll need to require 'backports/1.8.7' if in 1.8.6. 它是1.8.7的新功能,因此如果在1.8.6中,则require 'backports/1.8.7'

Note: I'm assuming you need to eval at all, because in your particular example, you can call that method directly, no? 注意:我假设您完全需要评估,因为在您的特定示例中,您可以直接调用该方法,不是吗?

SomeClass.has_many name.tableize.to_sym, :through=>:join_models

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM