From 1d06c3658c1e9e36e1b174609b627f22ce1137b9 Mon Sep 17 00:00:00 2001 From: Yordis Prieto Date: Tue, 25 Nov 2025 19:25:51 -0500 Subject: [PATCH] feat: add string support to Enum.value/1 Signed-off-by: Yordis Prieto --- CHANGELOG.md | 31 +++++++++++++++++++++++++++++++ lib/protobuf/dsl/enum.ex | 10 +++++++++- test/protobuf/dsl_test.exs | 11 +++++++++++ 3 files changed, 51 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d332a34f..fdfd794d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,36 @@ # Changelog +## v0.16.0 + +### Enhancements + + * Add `full_name/0` callback to proto messages for retrieving the full protobuf name. + + ```elixir + # For a message defined as: + # package my.package; + # message MyMessage { ... } + + MyPackage.MyMessage.full_name() + #=> "my.package.MyMessage" + ``` + + * Add support for enum `value/1` callback with string arguments. + + ```elixir + # For an enum defined as: + # enum Status { + # UNKNOWN = 0; + # ACTIVE = 1; + # INACTIVE = 2; + # } + + MyPackage.Status.value("ACTIVE") + #=> 1 + MyPackage.Status.value("INACTIVE") + #=> 2 + ``` + ## v0.15.0 ## Enhancements diff --git a/lib/protobuf/dsl/enum.ex b/lib/protobuf/dsl/enum.ex index ec0666b0..f3183ba6 100644 --- a/lib/protobuf/dsl/enum.ex +++ b/lib/protobuf/dsl/enum.ex @@ -4,6 +4,7 @@ defmodule Protobuf.DSL.Enum do alias Protobuf.{FieldProps, MessageProps} @callback value(atom()) :: integer() + @callback value(String.t()) :: integer() @callback value(tag) :: tag when tag: integer() @callback key(integer()) :: atom() | integer() @@ -39,12 +40,19 @@ defmodule Protobuf.DSL.Enum do end end + string_clauses = + for {atom, tag} <- message_props.field_tags do + quote do + def value(unquote(Atom.to_string(atom))), do: unquote(tag) + end + end + int_clause = quote do def value(tag) when is_integer(tag) and tag >= 0, do: tag end - [bodiless_clause] ++ atom_clauses ++ [int_clause] + [bodiless_clause] ++ atom_clauses ++ string_clauses ++ [int_clause] end defp defp_key_callback(message_props) do diff --git a/test/protobuf/dsl_test.exs b/test/protobuf/dsl_test.exs index 999a8efb..ce034efc 100644 --- a/test/protobuf/dsl_test.exs +++ b/test/protobuf/dsl_test.exs @@ -182,6 +182,17 @@ defmodule Protobuf.DSLTest do Foo.__message_props__().field_props[11] end + test "supports enum value with string" do + assert TestMsg.EnumFoo.value("A") == 1 + assert TestMsg.EnumFoo.value("B") == 2 + assert TestMsg.EnumFoo.value("C") == 4 + assert TestMsg.EnumFoo.value("D") == 4 + assert TestMsg.EnumFoo.value("E") == 4 + assert TestMsg.EnumFoo.value("UNKNOWN") == 0 + assert_raise FunctionClauseError, fn -> TestMsg.EnumFoo.value("F") end + assert_raise FunctionClauseError, fn -> TestMsg.EnumFoo.value("INVALID") end + end + test "ignores unknown options" do msg_props = Foo.__message_props__() assert msg_props.field_props[11].wire_type == 0