Skip to content

Instantly share code, notes, and snippets.

@hundredwatt
Created April 15, 2024 00:05

Revisions

  1. hundredwatt created this gist Apr 15, 2024.
    46 changes: 46 additions & 0 deletions literal_enum.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,46 @@
    # frozen_string_literal: true

    require "bundler/inline"

    gemfile(true) do
    source "https://rubygems.org"

    gem "rails"
    # If you want to test against edge Rails replace the previous line with this:
    # gem "rails", github: "rails/rails", branch: "main"

    gem "sqlite3"
    end

    require "active_record"
    require "minitest/autorun"
    require "logger"

    # This connection will do for database-independent bug reports.
    ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
    ActiveRecord::Base.logger = Logger.new(STDOUT)

    ActiveRecord::Schema.define do
    create_table :posts, force: true do |t|
    t.string :status
    end
    end

    class ApplicationRecord < ActiveRecord::Base
    primary_abstract_class

    def self.literal_enum(name = nil, values = nil, **options)
    if values.is_a?(Array)
    values = values.map { |value| [value] * 2 }.to_h
    end

    enum(name, values, **options)
    end
    end

    class Post < ApplicationRecord
    literal_enum :status, ['pending', 'accepted']
    end

    post = Post.create! status: 'accepted'
    p post.status_before_type_cast # => 'accepted'