简体   繁体   English

使用Ruby中的相同模块多次扩展对象

[英]Extending an object multiple times with the same module in Ruby

Given a class Klass and an instance k of this class: 给定一个Klass类和该类的一个实例k

class Klass
  def hello
    'Hello'
  end
end

k = Klass.new
k.hello        #=> "Hello"

I can extend this instance with a module to add methods to this specific instance without altering the whole class (ie all instances): 我可以使用模块extend该实例,以向该特定实例添加方法,而无需更改整个类(即所有实例):

module Mod
  def hello
    "#{super}, World!"
  end
end

k.extend(Mod)
k.hello        #=> "Hello, World!"

But what happens if I extend k multiple times with the same module? 但是,如果我用同一模块多次扩展k会发生什么?

k.extend(Mod)
k.extend(Mod)
k.extend(Mod)
k.hello        #=> "Hello, World!"

Are the subsequent calls ignored or is the object extended multiple times? 后续调用是否被忽略,或者对象被多次扩展?

To put it another way: is it "safe" to extend an object multiple times? 换句话说,多次扩展对象是否“安全”?

I think the subsequent calls are ignored (unless you have something deeper in mind). 我认为后续的调用将被忽略(除非您有更深的想法)。 The following result shows Mod only once in the ancestor list. 以下结果在祖先列表中仅显示一次Mod

class Klass; end
module Mod; end
k = Klass.new
k.extend(Mod)
k.extend(Mod)
k.extend(Mod)
k.singleton_class.ancestors
# => [#<Class:#<Klass:0x007f7787ef7558>>, Mod, Klass, Object, Kernel, BasicObject]

sawa already answered the actual question, but this could be relevant, too. sawa 已经回答了实际的问题,但这也可能是相关的。 Although the Mod is added only once to the object's (singleton class') ancestors, the extended callback is called every time: 尽管Mod仅添加一次到对象(单个类)的祖先,但是每次都调用extended回调:

class Klass
end

module Mod
  def self.extended(mod)
    puts "#{self} extended in #{mod}"
  end
end

k = Klass.new
k.extend(Mod)
#=> "Mod extended in #<Klass:0x007fabbb029450>"
k.extend(Mod)
#=> "Mod extended in #<Klass:0x007fabbb029450>"
k.extend(Mod)
#=> "Mod extended in #<Klass:0x007fabbb029450>"

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

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