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.
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).
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With