ruby - Can a class in a module use the attributes of the class that extends the module?

An example might be:

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

I've lost my @foo and @bar attributes in the nested classes within SharedStuff. Is there a way to get it without resorting to this?:

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

I know this isn't right because I still can't reach has_foo in the parent module. I'm sort of new to using mixins and modules in Ruby, is there a way to arrange this to get the methods in SharedStuff and the instance methods of the classes that extend it inside of the StuffGenerator?

1 Answer

  1. Kevin- Reply

    2019-11-13

    You can still inherit inside of modules. All I needed was the @foo and @bar attributes, so I just went to the BaseSource and got them. :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
    

Leave a Reply

Your email address will not be published. Required fields are marked *

You can use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>