Last active
June 26, 2024 00:03
-
-
Save osbre/9a024896f685037c7d4b51b0a2e3b5a7 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
# FallbackStiToBase | |
# | |
# This concern provides a customizable fallback mechanism for Single Table Inheritance (STI) in Rails. | |
# It allows specifying which types should raise an error when not found, while others fallback to the base class. | |
# | |
# Usage: | |
# class Action < ApplicationRecord | |
# include FallbackStiToBase | |
# validates :type, presence: true, inclusion: { in: %w[Value1 Value2 Value3] } | |
# fallback_excluded_types 'RemovedValue1', 'RemovedValue2' | |
# end | |
# | |
# Benefits: | |
# 1. Prevents errors for missing subclasses by falling back to the base class. | |
# 2. Raises errors for specified removed subclasses to avoid potential issues. | |
# 3. Allows for additional validation or behavior in the base class. | |
module FallbackStiToBase | |
extend ActiveSupport::Concern | |
class_methods do | |
def fallback_excluded_types(*types) | |
@fallback_excluded_types = types.map(&:to_s) | |
end | |
def sti_class_for(type_name) | |
type_name.constantize | |
rescue NameError | |
if @fallback_excluded_types&.include?(type_name) | |
raise | |
else | |
self | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Upd: published a Gem: https://github.com/osbre/sti_fallback