Last active
June 23, 2024 13:47
-
-
Save fsubal/c2c41900c333f2dc40d487d260e5fb52 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
module InheritByEnum | |
extend ActiveSupport::Concern | |
class_methods do | |
def inherit_by_enum(**options) | |
name, values = options.sole.to_a | |
plural_name = name.to_s.pluralize | |
self.inheritance_column = name | |
enum **options | |
define_method :find_sti_class do |value| | |
value_key = values.key(value.to_i) | |
"#{name}::#{value_key.to_s.camelize}".constantize | |
end | |
define_method :sti_name | |
values[name.demodulize.underscore] | |
end | |
end | |
end | |
end | |
class Book < ApplicationRecord | |
inherit_by_enum status: { draft: 'draft', published: 'published' } | |
end | |
class Book::Draft < Book | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment