一般的なメソッドをモジュールまたはクラスに移動し、別のモジュールの名前空間に含まれる新しいクラスにインクルード/継承させることで問題を解決しようとしています。同じモジュールの下に2つのクラスの名前空間がある場合、同じ名前空間の下にある限り、モジュール名を含めずに呼び出すことができます。しかし、私の名前空間の範囲の変更とは別のモジュールに含まれているメソッドがある場合、それを避ける理由や方法はわかりません。モジュールのスコープが正しくありません
たとえば、このコードの動作を返す「バー」:
module Foo
class Bar
def test_it
Helper.new.foo
end
end
end
module Foo
class Helper
def foo
'bar'
end
end
end
Foo::Bar.new.test_it
が、私はモジュールにメソッドのtest_itを移動した場合、それはもはや仕事doesntの:NameError:初期化されていない一定のミックスイン:: ::ヘルパー。
module Mixins; end
module Mixins::A
def self.included(base)
base.class_eval do
def test_it
Helper.new.foo
end
end
end
end
module Foo
class Bar
include Mixins::A
end
end
module Foo
class Helper
def foo
'bar'
end
end
end
Foo::Bar.new.test_it
さらに、class_evalがblockではなくstringを評価している場合、scopeはFooではなくFoo :: Barになります。
module Mixins; end
module Mixins::A
def self.included(base)
base.class_eval %q{
def test_it
Helper.new.foo
end
}
end
end
module Foo
class Bar
include Mixins::A
end
end
module Foo
class Helper
def foo
'bar'
end
end
end
Foo::Bar.new.test_it
誰でも知っていますか?
EDIT:
module Mixins; end
module Mixins::A
def self.included(base)
base.class_eval do
def test_it
_nesting::Helper
end
def _nesting
@_nesting ||= self.class.name.split('::')[0..-2].join('::').constantize
end
end
end
end
module Foo
class Helper
end
class Bar
include Mixins::A
end
end
module Foo2
class Helper
end
class Bar
include Mixins::A
end
end
Foo::Bar.new.test_it #=> returns Foo::Helper
Foo2::Bar.new.test_it #=> returns Foo2::Helper
嬉しいです! –