Skip to content

Instantly share code, notes, and snippets.

@osbre
Last active June 26, 2024 00:03
Show Gist options
  • Save osbre/9a024896f685037c7d4b51b0a2e3b5a7 to your computer and use it in GitHub Desktop.
Save osbre/9a024896f685037c7d4b51b0a2e3b5a7 to your computer and use it in GitHub Desktop.
# 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
@osbre
Copy link
Author

osbre commented Jun 26, 2024

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment