Created
April 30, 2020 22:17
-
-
Save qortex/14fef1895ace338acd3d1c71e7b5fabf 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
# frozen_string_literal: true | |
require 'sequel' | |
module QontrolDB | |
module SequelPlugins | |
# This Sequel Plugin stores all models that are created throughout the app, to make a list of | |
# them available to anyone who needs it. | |
# | |
# It works by creating a hook called whenever a class is created by inheriting from the | |
# `Sequel::Model` class (meaning a new Model is created in the application). This new class is | |
# thus remembered as a Business Domain Model. | |
# | |
# It is for example useful to freeze model classes as explained here: | |
# https://sequel.jeremyevans.net/rdoc/files/doc/code_order_rdoc.html#label-Finalize+Associations+and+Freeze+Model+Classes+and+Database | |
# | |
class ListModels | |
class << self | |
# @return [Array<Sequel::Model>] All models classes created throughout the app at call time | |
attr_reader :models | |
# Register a new class model that has been created | |
# | |
# @param [Class] model_klass | |
def register_new_model(model_klass) | |
@models ||= [] | |
@models << model_klass | |
end | |
end | |
module ClassMethods | |
# Calls when a model inherits from Sequel::Model with this plugin enabled, i.e. when a new | |
# Model class is created. | |
# | |
# So we take this opportunity to remember the class in the ListModels list. | |
# | |
# @param [Class] model | |
def inherited(model) | |
ListModels.register_new_model(model) | |
super | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment