模块中的类可以使用扩展模块的类的属性吗?

时间:2013-08-28 19:24:25

标签: 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
  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内扩展它的类的实例方法?

1 个答案:

答案 0 :(得分: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