amencarini
amencarini

Reputation: 609

Dynamic class loading: Is there a "method_missing" for classes in Ruby?

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

Answers (4)

Peter Saxton
Peter Saxton

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

Andrea Pavoni
Andrea Pavoni

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

Michael Kohl
Michael Kohl

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

edgerunner
edgerunner

Reputation: 14973

Maybe you can rescue an undefined constant error and load/create your classes.

Upvotes: -1

Related Questions