“扩展自我”与“module_function”相同吗?

时间:2021-06-14 23:18:38

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

#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