In development I am trying to gather all models within my app by including a method within ActiveRecord::Base classes so they can configure the models and it will give me a hook to add that model to a global array.
module EngineName
module ActiveRecordExtensions
extend ActiveSupport::Concern
included do
def self.inherited(klass) #:nodoc:
klass.class_eval do
def self.config_block(&block)
abstract_model = EngineName::AbstractModel.new(self)
abstract_model.instance_eval(&block) if block
EngineName::Models.add(abstract_model)
end
end
end
end
end
end
My EngineName::Models class is just a wrapper that holds all models.
module EngineName
class Models
class << self
def all
@models ||= []
end
alias_method :models, :all
def navigation
@models - excluded_navigation_models
end
def routed
@models - excluded_route_models
end
# Creates an array of models if none exists. Appends new models
# if the instance variable already exists.
def register(klass)
if @models.nil?
@models = [klass]
else
@models << klass unless @models.include?(klass) || excluded_models.include?(klass)
end
end
alias_method :add, :register
end
end
end
On each refresh though, the config_block method within my model gets called and in turn appends the same model over and over within my global array of models.
As you can see down below, whenever I loop through all my models, it will keep on appending itself.

Is there any way to cache certain classes within my engine? Or is there a flaw within my approach of registering models with a hook within the model itself?
The issue is that in your development environment your models get reloaded on every request so that changes to these classes take effect and you don’t have to re-boot your server every time you make a change to your source code. You can see this behavior in the console:
What this means is that when you call
@models.include?(klass)you are actually checking your current instantiation of that object against one from a previous request. What you’ll notice is that over time your memory gets bloated because these objects will not be deleted – since garbage collection will keep them around because of the reference to them in your @models instance variable. This won’t be a problem in production, because classes are only loaded once, but it will cause you problems in development.To get around this I would recommend doing something like this:
Using a hash will let you keep track of models by their names, and whenever a new version of a model comes around it will replace the old out-dated version. This should help in your development environment. To get a list of all the models you’ll simply use
@models.valuesand to get a list of the model names you’ll simply use@models.keys.