12

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.

4 Answers 4

18

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
Sign up to request clarification or add additional context in comments.

Comments

15

There's Module#const_missing:

http://apidock.com/ruby/Module/const_missing

I assume you can (ab)use that for your needs.

3 Comments

ops! I posted same answer just few seconds after :P
I take it you say (ab)use as it's far from a best practice? :) In case, any suggestion is more than welcome and appreciated.Anyway exactly what I was looking for, thanks a lot!
Oh, I didn't say that, it was more a little stab at all the metaprogramming that borders between use and abuse a lot of the time. More often than not I'm the guilty party in that... ;-)
4

there's const_missing method: it works like method_missing but it's about constants

http://ruby-doc.org/core/classes/Module.html#M000489

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.