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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extract type from Rails enums #20

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

tijmenb
Copy link

@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.
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.

None yet

1 participant