Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 367
amencarini Avatar asked Jun 22 '11 08:06

amencarini


People also ask

Does Ruby have class methods?

There are two standard approaches for defining class method in Ruby. The first one is the “def self. method” (let's call it Style #1), and the second one is the “class << self” (let's call it Style #2).

What is Define_method in Ruby?

define_method is a method defined in Module class which you can use to create methods dynamically. To use define_method , you call it with the name of the new method and a block where the parameters of the block become the parameters of the new method.

How is Ruby a MetaProgramming language?

MetaProgramming gives Ruby the ability to open and modify classes, create methods on the fly and much more. A few examples of metaprogramming in Ruby are: Adding a new method to Ruby's native classes or to classes that have been declared beforehand. Using send to invoke a method by name programmatically.


1 Answers

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
like image 117
Peter Saxton Avatar answered Nov 01 '22 17:11

Peter Saxton