일반적인 메서드를 모듈이나 클래스로 옮겨서 다른 모듈 아래에있는 네임 스페이스 인 새 클래스에 포함 시키거나 상속 시키려고합니다. 동일한 모듈 아래에 두 개의 클래스 네임 스페이스가있는 경우 동일한 네임 스페이스 아래에있는 한 모듈 이름을 포함하지 않고이를 호출 할 수 있습니다. 하지만 내 네임 스페이스 범위 변경과 다른 모듈에서 포함 된 메서드가 있고 왜 또는 어떻게 피하기 위해 모릅니다.모듈 스코프가 올바르지 않습니다.
예를 들면. 이 코드는 작동 반환 '바'
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을 이동하는 경우, 그것은 더 이상 작동 나던 : 나가서 설명하자면 NameError : 일정하게 유지 mixin 초기화되지 않은 :: :: 도우미.
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 대신 evaling 문자열 인 경우 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
누구든지 아이디어가 있습니까?
편집 :
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
솔루션을 얻을 수있어서 다행입니다! –