Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 360
Michael Lennox Avatar asked Apr 27 '16 15:04

Michael Lennox


People also ask

How do you find the constants in Ruby?

Ruby Constants Constants begin with an uppercase letter. Constants defined within a class or module can be accessed from within that class or module, and those defined outside a class or module can be accessed globally. Constants may not be defined within methods.

How do you access a module in Ruby?

A user can access the value of a module constant by using the double colon operator(::) as shown in the above example. If the user will define a method with def keyword only inside a module i.e. def method_name then it will consider as an instance method.

How do you call a class module in Ruby?

As with class methods, you call a module method by preceding its name with the module's name and a period, and you reference a constant using the module name and two colons.

Can a module contain a class Ruby?

A Ruby module can contain classes and other modules, which means you can use it as a namespace.


2 Answers

You can reference the class module being included into as self.class and the use const_get or just self.class::CONST, with the latter being slightly faster:

module M
  def foo
    self.class::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
like image 140
Vasfed Avatar answered Oct 02 '22 07:10

Vasfed


You can reference the class with self.class

module Foo
  def do_something
    self.class::Constant.each {|x| puts x}
  end
end

class Bar
  include Foo
  Constant = %w(Now is the time for all good men)
end

class Baz
  include Foo
  Constant = %w(to come to the aid of their country)
end

bar = Bar.new
bar.do_something
=>
Now
is
the
time
for
all
good
men
 => ["Now", "is", "the", "time", "for", "all", "good", "men"] 

baz = Baz.new
baz.do_something
=>
to
come
to
the
aid
of
their
country
 => ["to", "come", "to", "the", "aid", "of", "their", "country"]
like image 21
SteveTurczyn Avatar answered Oct 02 '22 08:10

SteveTurczyn