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

Extract type from Rails enums #20

Merged
merged 2 commits into from
Aug 23, 2024

Conversation

tijmenb
Copy link
Contributor

@tijmenb tijmenb commented Feb 27, 2024

Description 📖

This adds support for enums in Rails. Defined enums will be converted to a union type with its allowed values.

Background 📜

Rails enums are currently converted to "any" types. In our own app we've been adding manual types with something like this:

class SongSerializer < BaseSerializer
  attributes(
    :id,
    :title,
    genre: { type: "'pop'|'rock'|'classical'" },
  )
end

This PR aims to make it automatic.

The Fix 🔨

This extracts the possible values for the enum and adds them as a type:

class Song < ApplicationRecord
  belongs_to :composer
  has_many :video_clips

+  enum genre: { disco: "disco", rock: "rock", classical: "classical" }
+  enum tempo: %w[slow medium fast]
end
export default interface Song {
  id: number
  composer: Composer
+  genre: "disco" | "rock" | "classical"
+  tempo: "slow" | "medium" | "fast"
  title?: string
}

I've added a test for the integer-enum as well as string-enum.

The added code in the generator is mildly atrocious - perhaps we can pass in the model here? Feedback welcome.

This adds support for enums in Rails. Defined enums will be converted
to a union type with it's allowed values.
@jamespearson
Copy link

Any idea when this could be merged?

@manufaktor
Copy link

This would be an awesome addition to the library 👍

enums = model.try(:defined_enums)

if enums
enum_values = enums[key].to_h.keys
Copy link
Owner

Choose a reason for hiding this comment

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

Using key here means that we would lose type inference when using the alias feature (tempo: {as: :beat}).

Adding a commit with a fix, and slight refactoring, otherwise looks great, thanks! 😃

@ElMassimo
Copy link
Owner

This is a nice addition, thanks @tijmenb!

@ElMassimo ElMassimo merged commit 49dc61d into ElMassimo:main Aug 23, 2024
0 of 7 checks passed
ElMassimo added a commit that referenced this pull request Aug 23, 2024
ElMassimo added a commit that referenced this pull request Aug 23, 2024
ElMassimo added a commit that referenced this pull request Aug 23, 2024
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.

4 participants