I need to define the constant in the module that use the method from the class that includes this module:
module B
def self.included(base)
class << base
CONST = self.find
end
end
end
class A
def self.find
"AAA"
end
include B
end
puts A::CONST
But the compiler gives the error on the 4th line.
Is there any other way to define the constant?
The more idiomatic way to achieve this in Ruby is:
What you were doing (class << base) actually puts you into the context of A’s
metaclass, not A itself. Thefindmethod is on A itself, not its metaclass. The thing to keep in mind is that classes are themselves objects, and so have their own metaclasses.To try to make it clearer:
Not sure if that helps, but if you don’t understand it, you can still use the class_eval idiom above.