literal
literal copied to clipboard
Make the rails enum integration aware of the original type
This change makes the :literal_enum attribute type, type-aware of the attribute that it is replacing.
Additionally it adds a literal_enum macro to ActiveRecord::Base that delegates to attribute and figures out the underlying attribute type.
My concern here is with calling type_for_attribute at class evaluation time is going to trigger a connection to the DB. This change broke my reproduction script because I created the database after defining the model. But this change makes the model definition require the database to be set up already.
Unfortunately I don't think we can lazy evaluate the type_for_attribute because after the call to attribute it's type will have changed to :literal_enum.
That's awesome! would be super awesome if literal_enum will actually work similar to enum:
class MyEnum < Literal::Enum(Integer)
Foo = new(1)
Bar = new(2)
end
class Example < ApplicationRecord
literal_enum :x, MyEnum, suffix: true, validate: { allow_nil: true }
end
My current problem is that, when I use something like:
def literal_enum(name, literal_enum, **)
mapping = literal_enum.to_h do |o|
[literal_enum.names.fetch(o).to_s.underscore, o.value]
end
enum(name, mapping, **)
end
I get Rails enum good parts like: example.foo?, or Example.bar.to_a; but loose ability to get underlying value in a good way. I can live without those scopes and stuff, but I want model to be validateble, so that when wrong value passed - I can show an error.