模块中的"extend-self"和module_function:name_of_method之间有什么区别?
示例:
module Foo
def bar
puts 'hi from bar'
end
def buu
puts 'hi from buu'
end
extend self
end
与
module Foo
def bar
puts 'hi from bar'
end; module_function :bar
def buu
puts 'hi from buu'
end; module_function :buu
end
module_function在什么时候会等价于扩展self?
现在,我似乎主要使用"扩展自我",几乎从来没有module_function。
extend self
将所有方法添加为静态方法,但它们仍然是模块方法。这意味着,当您从一个类扩展模块时,该类将获得这些方法。
module_function
除了使该方法成为模块方法之外,还使原始方法私有化。这意味着您将无法从扩展模块的对象外部使用这些方法。
你可以在这个例子中看到区别:
module Foo
def bar
puts 'hi from bar'
end
def buu
puts 'hi from buu'
end
extend self
end
module Bar
def bar
puts 'hi from bar'
end; module_function :bar
def buu
puts 'hi from buu'
end; module_function :buu
end
class A
extend Foo
end
class B
extend Bar
end
Foo::bar
A::bar
Bar::bar
B::bar #Error: private method `bar' called for B:Class (NoMethodError)