最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

ruby - How do I resolve the `Dynamic constant references` error in Sorbet? - Stack Overflow

programmeradmin1浏览0评论

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 badges
Add a comment  | 

1 Answer 1

Reset to default 3

I 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
发布评论

评论列表(0)

  1. 暂无评论