Michael Lennox Michael Lennox - 7 months ago 13
Ruby Question

Ruby: How to access a constant from the class a module is included into

I'm trying to access a constant held within various classes in a module which I am including into them. As a basic example

module foo
def do_something_to_const
CONSTANT.each { ... do_something ... }
end
end

class bar
include foo

CONSTANT = %w(I want to be able to access this in foo)
end

class baz
include foo

CONSTANT = %w(A different constant to access)
end


As the logic for the module is shared across multiple classes I'd like to be able to just refer to the constant (the name of which stays the same in each class, but the contents vary). How would I go around doing this?

Answer

Use const_get:

module M
  def foo
    self.class.const_get :CONST
  end
end

class A
  CONST = "AAAA"
  include M
end

class B
  CONST = "BBBB"
  include M
end

puts A.new.foo # => AAAA
puts B.new.foo # => BBBB