protobuf icon indicating copy to clipboard operation
protobuf copied to clipboard

ruby: Allow calling `resolve` with an `Integer`, or make `try_resolve` method

Open jez opened this issue 7 months ago • 3 comments

What language does this apply to?

Ruby

Describe the problem you are trying to solve.

Sometimes people write code like this:

foo = my_message.foo                   # returns Symbol or Integer
foo_int = MyMessage::Foo.resolve(foo)  # takes Symbol returns an Integer

What they want is to operate uniformly on Integer's (for example, to be able to case/when over the list of enum value constants:

case foo_int
when MyMessage::Foo::X
when MyMessage::Foo::Y
end

The problem is that resolve raises an exception if given an Integer.

Describe the solution you'd like

I would like a method that can be used to coerce an enum value to an Integer:

def self.try_resolve(sym_or_int)
  case sym_or_int
  when Symbol then resolve(sym_or_int)
  when Integer then sym_or_int
  else raise TypeError.new("wrong argument type #{sym_or_int.class} (expected Symbol or Integer)")
  end
end

MyMessage::Foo.resolve(my_message.foo)

Describe alternatives you've considered

  1. Hijack resolve for this, so that instead of raising an exception (the current behavior) it just returns the argument if it's an Integer
  2. Add a new try_resolve method.

Additional context Add any other context or screenshots about the feature request here.

I've also considered monkey patching a method that adds this just for our project, but there is no common superclass for enum modules. We have ~thousands of proto files, which means we'd need to generate methods for each of these, at which point it would be better to have this in protoc itself rather than some custom plugin.

jez avatar May 12 '25 18:05 jez

We triage inactive PRs and issues in order to make it easier to find active work. If this issue should remain active or becomes active again, please add a comment.

This issue is labeled inactive because the last activity was over 90 days ago. This issue will be closed and archived after 14 additional days without activity.

github-actions[bot] avatar Sep 05 '25 10:09 github-actions[bot]

This issue remains one of the biggest points of confusion among users of the protobuf gem at Stripe.

jez avatar Sep 05 '25 15:09 jez

I took a look at this yesterday, and I find very few test expectations for resolve, which leads me to believe that the current behavior of raising an exception for a int argument is not load bearing and could thus be relaxed. I would be in favor of updating the behavior of resolve rather than adding a new API.

@jez - would you be up for creating a PR for this?

JasonLunn avatar Oct 29 '25 14:10 JasonLunn