简体   繁体   English

ruby:can模块可以自动执行初始化代码吗?

[英]ruby: can module execute initialization code automatically?

I've put some functionality in a module, to be extended by an object. 我在一个模块中放了一些功能,由一个对象扩展。 I'd like the functionality to be executed automatically when the module is extended. 我想在扩展模块时自动执行功能。 However, it has to be executed in the context of the instance, not Module. 但是,它必须在实例的上下文中执行,而不是在Module中执行。

module X
   extend self

   @array = [1,2,3]

end
obj.extend(X)

Currently, @array does not get created in the instance. 目前,@ array未在实例中创建。 I don't wish to force the developer to call some initialization method, since then for each Module he needs to know the name of a unique method to call. 我不希望强制开发人员调用一些初始化方法,因为对于每个模块,他需要知道要调用的唯一方法的名称。 Is this possible ? 这可能吗 ?

You can use Module#extended hook for execution code on extension and BasicObject#instance_exec (or BasicObject#instance_eval ) for executing arbitrary code in context of extended object: 您可以在扩展上使用Module#extended hook作为执行代码,使用BasicObject #instance_exec (或BasicObject #instance_eval )在扩展对象的上下文中执行任意代码:

module X
  def self.extended(obj)
    obj.instance_exec { @array = [1,2,3] }
  end
end

class O
  attr_reader :array
end

obj = O.new

obj.array                                 # => nil

obj.extend(X)

obj.array                                 # => [1, 2, 3]

Show this article 显示这篇文章

module Math
  def self.extended(base)
    # Initialize module.
  end
end

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

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