Skip to content

Instantly share code, notes, and snippets.

@fsubal
Last active June 23, 2024 13:47
Show Gist options
  • Save fsubal/c2c41900c333f2dc40d487d260e5fb52 to your computer and use it in GitHub Desktop.
Save fsubal/c2c41900c333f2dc40d487d260e5fb52 to your computer and use it in GitHub Desktop.
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