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?
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.
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.
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.
A Ruby module can contain classes and other modules, which means you can use it as a namespace.
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
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With