Reputation: 609
On a Rails application I'm working on, I have a model "Type" that relates to the single-table-inheritance model "Node": any possible subclass of Node is defined as a Type in the types table.
Right now this is made possible loading all classes in an initializer, but I'd like to load the subclasses only when they are required.
The best solution I can think of would be having a fallback on an uninitialized constant that would check if that constant can represent a class in the application, something similar to what method_missing does.
I'd like some advice on how and where to define this logic, or if there's a better solution altogether.
Upvotes: 12
Views: 6222
Reputation: 4676
I don't know if this is new but as I thought it was worth adding. It is possible to use method missing as a class method
class Example
def method_missing(method_name, *arguments, &block)
puts 'needs this instance method'
end
def self.method_missing(method_name, *arguments, &block)
puts 'needs this class method'
end
end
Upvotes: 18
Reputation: 5311
there's const_missing method: it works like method_missing but it's about constants
http://ruby-doc.org/core/classes/Module.html#M000489
Upvotes: 4
Reputation: 66837
There's Module#const_missing
:
http://apidock.com/ruby/Module/const_missing
I assume you can (ab)use that for your needs.
Upvotes: 15
Reputation: 14973
Maybe you can rescue
an undefined constant error and load/create your classes.
Upvotes: -1