renum
renum copied to clipboard
rails integration to store int
I've just pulled this Gem into our rails app, works perfectly.
Only thing is I did not use the rails integration because we save the value in the DB in its int form.
It would be great if one could define the to and from transformations so that we can hydrate the int value from the DB to an enum, and back.
Note that our int value isn't the index, i.e our C# enum looks something like:
enum EventType
{
Unknown = 0,
EventA1 = 11,
EventA2 = 12,
EventB1 = 21,
EventB2 = 22,
...
}
And its rails counterpart looks something like:
enum :EventType do
attr_reader :value
attr_reader :label
def init(value, label)
@value = value
@label = label
end
def self.from_value(value)
EventType.detect {|t| t.value == value}
end
Unknown(0, "Unknown")
EventA1(11, "...")
EventA2(12, "...")
EventB1(21, "...")
EventB2(22, "...")
end
And in the database we want to store the .value
value
ActiveRecord's serialize will take as a second argument anything with dump
and load
methods, so that gives us a pretty good way to do what you're looking for.
I just added Renum::NameSerializer and Renum::IndexSerializer. Neither are what you want, but take a look, and you can see how easy it is to create your own.
As long as you always assign the correct type, things work great. Renum::NameSerializer also allows you to assign a string (which seemed handy for populating from params), but then (based on some quick testing) the attribute value will remain a string until you save, at which point it will become the proper EnumeratedValue. Not ideal.
If you want to avoid the string issue I just mentioned, you could create a writer method like constantize_attribute does.