Jainathan Leung
Jainathan Leung

Reputation: 1157

Inheritance and Extension in ruby

I've been playing with ruby and have a bit in my understanding of inheritance and mixins. Consider the following code:

module Base
  class Parent
    def foo
      "hello parent"
    end
  end

  module Extension
    module Extender
      def bar
        "hello extended"
      end
    end
  end
  module Tasks
    class Child < Base::Parent
      extend Base::Extension::Extender
      def blah
        puts "blah"
        puts foo
        puts self.bar
      end
    end
  end
end

Base::Tasks::Child.new().blah

blah fails at 'bar', claiming it's undefined. The context for this is that I want to use methods from Parent, but pull in some options and/or configuration from Extender that may be used in Parent as well. With this setup, I'd expect bar to be pulled into Child as a class variable, but clearly, it isn't.

Is there a better way to organize this, or am I misunderstanding how extend works?

Upvotes: 2

Views: 48

Answers (1)

user229044
user229044

Reputation: 239250

You need include to make bar an instance method, not extend. With extend, you've made bar a class-level method; you'd have to access it via Child.bar.

So either of these:

class Child < Base::Parent
  extend Base::Extension::Extender
  def blah
    puts Child.bar

or

class Child < Base::Parent
  include Base::Extension::Extender
  def blah
    puts self.bar

Upvotes: 5

Related Questions