我的情況是目前:
module Base
module A
include Base::B
end
end
module Base
module B
module_function
def my_method
...
end
end
end
然后我的測驗:
Rspec.describe Base::A do
describe '.my_method' do
it 'does something'
...
end
end
end
問題:
無方法錯誤。Base::A:Module 的未定義方法“my_method”
我錯過了什么?提前致謝!
uj5u.com熱心網友回復:
module Base
module B
module_function
def my_method
"you've found me!"
end
end
end
module Base
module A
include Base::B
end
end
module_function讓我們通過定義一個單例方法來呼叫模塊上的方法:
>> Base::B.singleton_methods
=> [:my_method]
>> Base::B.my_method
=> "you've found me!"
它也變成my_method了一個私有方法,這是你在“包含”或“擴展”時得到的方法:
>> Base::B.private_instance_methods
=> [:my_method]
# NOTE: we can call this version of `my_method` by including or
# extending the module in a class
class Included
include Base::B
end
>> Included.private_instance_methods
=> [:my_method, ...]
>> Included.new.send(:my_method)
=> "you've found me!"
class Extended
extend Base::B
end
# this would be a private class method
>> Extended.private_methods
=>[:my_method, ...]
>> Extended.send(:my_method)
=> "you've found me!"
Base::B如果包含在Base::A模塊中,則適用相同的規則:
>> Base::A.private_instance_methods
=> [:my_method]
# NOTE: we cannot call `my_method` on the module, because we do not get a
# singleton method
>> Base::A.singleton_methods
=> []
# there is the expected instance method, made private by using `module_function`
>> Base::A.private_instance_methods
=> [:my_method]
# only we can't call `.new` on a module.
>> Base::A.new.send(:my_method)
`<main>': undefined method `new' ...
由于我們無法在模塊外初始化實體,我們可以通過擴展將實體方法轉換為類Base::A方法self。
module Base
module A
include Base::B
extend self
end
end
>> Base::A.private_methods
=> [:my_method, ...]
>> Base::A.send(:my_method)
=> "you've found me!"
或Base::B從頭開始:
module Base
module A
extend Base::B
end
end
>> Base::A.send(:my_method)
=> "you've found me!"
module_function相當于:
module Base
module C
# NOTE: singleton method stays in this module
def self.my_method
"singleton my_method"
end
private
# NOTE: instance method gets included/extended
def my_method
"private instance my_method"
end
end
end
Base::C.my_method # => "singleton my_method"
Module.new.extend(Base::C).send(:my_method) # => "private instance my_method"
Class.new.extend(Base::C).send(:my_method) # => "private instance my_method"
Class.new.include(Base::C).new.send(:my_method) # => "private instance my_method"
https://ruby-doc.org/core-3.1.2/Module.html#method-i-module_function
https://ruby-doc.org/core-3.1.2/Module.html#method-i-include
https://ruby-doc.org/core-3.1.2/Object.html#method-i-extend
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/490985.html
上一篇:【學習筆記】WPF-01:前言
