How do I resolve the Dynamic constant references
error in Sorbet?
module A
CONSTANT = { x: 1, y: 0 }.freeze
end
module B
CONSTANT = { x: 0, y: 1 }.freeze
end
class C
def initialize(kind)
@kind = kind
end
def target_module
@kind == 'a' ? A : B
end
def foo
p target_module::CONSTANT # error: Dynamic constant references are unsupported
end
end
C.new('a').foo # -> {x: 1, y: 0}
Suppose module A and B have constant CONSTANT in the same structure.
When I try to reference the constants dynamically in class C, which handles those modules, I get the error Dynamic constant references are unsupported
.
How can I solve this problem?
(I have a feeling that I should just use abstract and change the references to the constants to methods.)
There is no abstract for constants, is there?
Sorbet Playground Link
How do I resolve the Dynamic constant references
error in Sorbet?
module A
CONSTANT = { x: 1, y: 0 }.freeze
end
module B
CONSTANT = { x: 0, y: 1 }.freeze
end
class C
def initialize(kind)
@kind = kind
end
def target_module
@kind == 'a' ? A : B
end
def foo
p target_module::CONSTANT # error: Dynamic constant references are unsupported
end
end
C.new('a').foo # -> {x: 1, y: 0}
Suppose module A and B have constant CONSTANT in the same structure.
When I try to reference the constants dynamically in class C, which handles those modules, I get the error Dynamic constant references are unsupported
.
How can I solve this problem?
(I have a feeling that I should just use abstract and change the references to the constants to methods.)
There is no abstract for constants, is there?
Sorbet Playground Link
Share Improve this question asked Feb 7 at 8:23 pvcresinpvcresin 792 silver badges6 bronze badges1 Answer
Reset to default 3I would make the constant call more explicit like you already did in the target_module
method:
def foo
if @kind == 'a'
A::CONSTANT
else
B::CONSTANT
end
end
Or I would implement appropriate getter methods to not call the “internal” constants directly:
module A
CONSTANT = { x: 1, y: 0 }.freeze
def self.bar = CONSTANT
end
module B
CONSTANT = { x: 0, y: 1 }.freeze
def self.bar = CONSTANT
end
def foo
p target_module.bar
end