Created
April 15, 2024 00:05
-
-
Save hundredwatt/9742581230a320eaac008ef01e90f156 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment