Ruby 模块中的类能否使用扩展模块的类的属性?
例如:Ruby 模块中的类能否使用扩展模块的类的属性?,ruby,class,inheritance,module,extends,Ruby,Class,Inheritance,Module,Extends,例如: module SharedStuff def has_foo !@foo.nil? end class StuffGenerator def initialize # super can't work here end # Will return nil. def try_foo @foo end end end class NeedsSharedStuff < BaseSource
module SharedStuff
def has_foo
!@foo.nil?
end
class StuffGenerator
def initialize
# super can't work here
end
# Will return nil.
def try_foo
@foo
end
end
end
class NeedsSharedStuff < BaseSource
include SharedStuff
def initialize
super
end
end
class AlsoSharedStuff < OtherSource
include SharedStuff
def initialize
super
end
end
class BaseSource
attr_reader :foo, :bar
def initalize
@foo, @bar = get_foo, get_bar
end
end
class OtherSource < BaseSource
def initialize
super
end
def extra_stuff
# whatever...
end
end
我知道这是不对的,因为我仍然无法访问父模块中的has\u foo。
我对在Ruby中使用mixin和modules有点陌生,有没有一种方法可以安排它来获得
SharedStuff
中的方法以及在StuffGenerator
中扩展它的类的实例方法?您仍然可以在模块内部继承。我所需要的只是@foo
和@bar
属性,所以我只需转到BaseSource
并获取它们<代码>:D
module SharedStuff
def has_foo
!@foo.nil?
end
class StuffGenerator < BaseSource
def initialize
super
end
# Will return foo.
def try_foo
@foo
end
end
end
模块SharedStuff
def有_foo
!@零?
结束
类StuffGenerator
module SharedStuff
def has_foo
!@foo.nil?
end
class StuffGenerator < BaseSource
def initialize
super
end
# Will return foo.
def try_foo
@foo
end
end
end