types_from_serializers icon indicating copy to clipboard operation
types_from_serializers copied to clipboard

Extract type from Rails enums

Open tijmenb opened this issue 1 year ago • 1 comments

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.

tijmenb avatar Feb 27 '24 12:02 tijmenb

Any idea when this could be merged?

jamespearson avatar Jul 04 '24 16:07 jamespearson

This would be an awesome addition to the library 👍

manufaktor avatar Aug 22 '24 20:08 manufaktor

This is a nice addition, thanks @tijmenb!

ElMassimo avatar Aug 23 '24 14:08 ElMassimo