Inheriting Constants inside a Ruby module

inheritance, module, ruby

Solution

module BaseMod
  def what_am_i
    puts self.class::OUTPUT
  end
end

module Tall
  OUTPUT = "I am tall"
  include BaseMod
end

module Short
  OUTPUT = "I am short"
  include BaseMod
end

class Person
  def initialize(type)
    if type =~ /short/i
      self.class.send(:include, Short)
    else
      self.class.send(:include, Tall)
    end
  end
end

p = Person.new "short"
p.what_am_i

Edit: The code above doesn't actually work:

p = Person.new "short"
p.what_am_i
>> I am short
p = Person.new "tall"
p.what_am_i
>> I am tall
p = Person.new "short"
p.what_am_i
>> I am tall

Here is another attempt:

module BaseMod
  def self.included(base)
    base.send(:define_method, :what_am_i) do
      puts base::OUTPUT
    end
  end
end

module Tall
  OUTPUT = "I am tall"
  include BaseMod
end

module Short
  OUTPUT = "I am short"
  include BaseMod
end

class Person
  def initialize type
    if type =~ /short/i
      extend Short
    else
      extend Tall
    end
  end
end

p = Person.new "short"
p.what_am_i
p = Person.new "tall"
p.what_am_i
p = Person.new "short"
p.what_am_i

Problem

In Ruby, I'm trying to create a class, which based on a value given during initialization will inherit from one of the following modules. I would like to make a base module that both these modules inherit from that contain common methods that use constants defined in the modules that inherit it. Example: ``` module BaseMod def what_am_i puts OUTPUT end end module Tall OUTPUT = "I am tall" include BaseMod end module Short OUTPUT = "I am short" include BaseMod end class Person def initialize type if type =~ /short/i extend Short else extend Tall end end end p = Person.new "short" p.what_am_i ``` My issue is that when "p.what_am_i" is called I get the following error: ``` NameError: uninitialized constant BaseMod::OUTPUT const_missing at org/jruby/RubyModule.java:2642 what_am_i at test_logic2.rb:3 (root) at test_logic2.rb:28 ``` I'm also wondering if there's a better way to go about doing this.

Original source