Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

enum.to_hash key by name, not tag #276

Open
mooreniemi opened this issue Dec 14, 2015 · 1 comment
Open

enum.to_hash key by name, not tag #276

mooreniemi opened this issue Dec 14, 2015 · 1 comment

Comments

@mooreniemi
Copy link

I'm using an Enum to represent the list of HTTP verbs. When I serialize this, I'd like to see the tag, not the integer (other places in the system use the integer, but this is for documentation). Is there any way I can call .to_hash on an enum value and return the name rather than the tag/int?

Ie, Mason::HTTPVerb::PATCH.name is always cast to 3 when .to_hash is called, but I'd like this version of the representation to show :PATCH instead. Possible?

        {
          "z:edit": Mason::Edit.new(
            {
              href: "http://localhost:9292/#{path}/#{params[:item_id]}",
              method: Mason::HTTPVerb::PATCH.name
            }
          ).to_hash
        }

Desired output:

 {:"z:edit"=>{:href=>"http://localhost:9292/animals/767", :method=>:PATCH}}

Current output:

 {:"z:edit"=>{:href=>"http://localhost:9292/animals/767", :method=>3}}
@film42
Copy link
Member

film42 commented Jan 9, 2016

Hey, thanks for opening an issue! Currently, there isn't a way of doing this. When any enum field setter is called, protobuf will convert that value into an enum class. Whenever you attempt to encode something, the behavior is to call #to_i. Based on your example, though, you can remove the Mason::Edit protobuf model, and get what you want by building the hash directly.

Also, I'm not sure there's a strong use-case for adding this feature. I think if you're sending from a protobuf client to some protobuf server, then you won't need to worry about losing value of the enum type. If you're sending json from protobuf, then building a hash from scratch, or using some other tool like rabl might be your solution (my opinion).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants