Last active
July 17, 2024 05:18
-
-
Save fsubal/bb3428c1338ddf24a20fba1bdd0265bb 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
class Provider | |
include FindSubclassBySlug | |
end | |
module FindSubclassBySlug | |
extend ActiveSupport::Concern | |
class SubclassNotFound < StandardError; end | |
included { load_subclasses! } | |
class_methods do | |
def namespace | |
name.deconstantize.underscore | |
end | |
def slug | |
name.demodulize.underscore | |
end | |
def find(slug) | |
subclasses.find { |klass| klass.slug == slug }&.new | |
end | |
def find!(slug) | |
find(slug) || raise(SubclassNotFound) | |
end | |
private | |
def load_subclasses! | |
Dir.glob("#{Rails.root}/app/models/#{namespace}/*.rb").each do |file| | |
"#{namespace}/#{File.basename(file, '.rb')}".camelize.constantize | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment