Skip to content

Instantly share code, notes, and snippets.

@fsubal
Last active July 17, 2024 05:18
Show Gist options
  • Save fsubal/bb3428c1338ddf24a20fba1bdd0265bb to your computer and use it in GitHub Desktop.
Save fsubal/bb3428c1338ddf24a20fba1bdd0265bb to your computer and use it in GitHub Desktop.
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