一个例子可能是:
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
我在. @foo
_ 有没有办法在不诉诸于此的情况下获得它?:@bar
SharedStuff
module SharedStuff
def has_foo
@foo.empty?
end
def stuff_generator
StuffGenerator.new @foo, @bar
end
class StuffGenerator
attr_reader :foo, :bar
def initialize(foo, bar)
@foo, @bar = foo, bar
end
def try_foo
@foo
end
end
end
我知道这是不对的,因为我仍然无法访问has_foo
父模块。我对在 Ruby 中使用 mixins 和模块有点陌生,有没有办法安排它来获取方法SharedStuff
以及在 内部扩展它的类的实例方法StuffGenerator
?