Ruby 元编程问题

标签 ruby metaprogramming

当我调用 self.class.instance_variable_set("@var", ...)从类方法内部,该变量实际存储在哪里?是在类里面吗?在那个类的实例上?我似乎无法通过以下任何方式找到它:

e = Example.new
e.instance_variables
e.class.class_variables

我什至尝试使用 (class << self; self; end)技巧,但我找不到任何东西(http://ruby-metaprogramming.rubylearning.com/html/seeingMetaclassesClearly.html)。

这是代码片段(可以按我的需要工作)但我不确定为什么它可以工作:)

module HandyModule
  def self.included(base)
    base.extend ClassMethods
  end
  module ClassMethods
    def use_template(template_name)
      self.class.instance_variable_set("@_template", template_name)
    end
    def build(attributes = {})
      template_name = self.class.instance_variable_get("@_template")
      # do stuff with the template
    end
  end
end

class Example
  include HandyModule
  use_template :contact_form
end

基本上我可以包含这个方便的模块,然后我有一个名为 use_template 的类方法我可以用它指定我的构建方法要使用的模板。

最佳答案

当您在类定义中调用 use_template 时,self 是类 Example。当你调用self.class时,它是Example.class,或者Class。您将实例变量定义为类的类。

class Class
  p @_template
end
# prints :contact_form

您可能应该只使用 self 而不是 self.class

关于Ruby 元编程问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5931067/

相关文章:

ruby 字符串#to_class

ruby - 为什么 STOMP、ActiveMQ 和 Vagrant 不能在我的系统上运行?

python - 为什么 Time.utc 在 OS X 上的 Ruby 中的 fork 进程中变慢(而不是在 Python 中)?

ruby-on-rails - 英雄数据库 :pull not working

Ruby Sinatra - 为公共(public)文件夹中的文件添加自定义路由

ruby - 如何在某个类的祖先中检测我的匿名模块

Ruby 打印当前可见性

ruby - 在 config.rb 中扩展类时如何访问 Middleman 模板助手?

scala - 在宏扩展时生成函数

c# - 元编程 : write in one language X, C#、PHP、Java、C 等多种语言交叉编译