ruby T::如果使用了无效的枚举,枚举将引发未初始化的常量,而不是引发类型使用了无效枚举的错误

roejwanj  于 12个月前  发布在  Ruby
关注(0)|答案(1)|浏览(128)

在我们的应用程序中,我们在按钮组件上使用Enum for变量:

class ButtonComponent
  sig do
    params(
      button_variant: ButtonVariant
    ).void
  end
  def initialize(button_variant: ButtonVariant::Primary)
end

枚举如下:

class ButtonComponent
  class ButtonVariant < T::Enum
    extend T::Sig

    enums do
      Primary = new
      Secondary = new
      Tertiary = new
    end

    sig { returns(String) }
    def css_class
      case self
      when Primary
        'btn--primary'
      when Secondary
        'btn--secondary'
      when Tertiary
        'btn--tertiary'
      else
        T.absurd self
      end
    end
  end
end

现在,如果我们传入一个无效的对象:

render ButtonComponent.new(button_variant: ButtonComponent::UNKNOWN)

我们从Sorbet得到一个关于传递的类型不正确的错误:

Parameter 'button_variant': Expected type ButtonComponent::ButtonVariant

然而,如果我们传入正确的类型,但一个无效的枚举:

render ButtonComponent.new(button_variant: ButtonComponent::ButtonVariant::UNKNOWN)

我们只得到一个错误,常数是未知的:

uninitialized constant ButtonComponent::ButtonVariant::UNKNOWN

难道Sorbet不应该引发一个Enum无效的错误,而不是抛出一个关于未初始化常量的更一般的错误吗?
我们希望错误会更加明确,这样开发人员就可以清楚地看到问题所在。invalid 'enum' used for type ButtonComponent::ButtonVariant .我们是否错误地使用了enum,或者这是Sorbet中的预期行为?

uplii1fm

uplii1fm1#

下面是一个较小的例子(见sorbet.run):

# typed: true
class Foo < T::Enum
  enums do
    BAR = new('bar')
  end
end

Foo::BAR
Foo::Zoo
#    ^ Unable to resolve constant Zoo https://srb.help/5002

截至2023-09-11,Sorbet认为这是一个未解决的常数,因此这是预期的行为。
您可以在sorbet's GitHub中报告此问题,它将被考虑进行修复,或者您将获得关于此问题无法修复的原因的更详细的解释。

相关问题