Skip to content

Conversation

willcosgrove
Copy link

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.

@ixti
Copy link
Contributor

ixti commented Apr 15, 2025

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.


class Literal::Rails::EnumType < ActiveModel::Type::Value
def initialize(enum)
def initialize(enum, subtype)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is the supertype not the subtype.

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

Successfully merging this pull request may close these issues.

3 participants