“擴展自我”與“module_function”相同嗎?

[英]Is “extend self” the same as “module_function”?


extend self and module_function are two ruby ways to make it so you can call a method on a module and also call it if you include that module.

擴展self和module_function是實現它的兩種ruby方法,因此可以在模塊上調用方法,如果包含該模塊,也可以調用該方法。

Are there any differences between the end results of those ways?

這些方法的最終結果有什么不同嗎?

1 个解决方案

#1


54  

module_function makes the given instance methods private, then duplicates and puts them into the module's metaclass as public methods. extend self adds all instance methods to the module's singleton, leaving their visibilities unchanged.

module_function使給定的實例方法成為私有的,然后復制並將它們作為公共方法放入模塊的元類中。擴展self將所有實例方法添加到模塊的單例,保持其可見性不變。

module M
  extend self

  def a; end

  private
  def b; end
end

module N
  def c; end

  private
  def d; end

  module_function :c, :d
end

class O
  include M
  include N
end

M.a
M.b  # NoMethodError: private method `b' called for M:Module
N.c
N.d
O.new.a
O.new.b  # NoMethodError: private method `b' called for O
O.new.c  # NoMethodError: private method `c' called for O
O.new.d  # NoMethodError: private method `d' called for O

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2010/03/01/7302318bf6b7eed304a7ed4062f58087.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com