0

一个例子可能是:

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_ 有没有办法在不诉诸于此的情况下获得它?:@barSharedStuff

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

4

1 回答 1

0

您仍然可以在模块内部继承。我所需要的只是@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
于 2013-08-28T20:06:20.810 回答