Home Play Pinja Bobbity flop

A blog about Ruby, Rails and other Tech. Mostly.

Back to blog

12th Jul 2004, 7:18am
Creating classes on the fly

This Ruby fragment is so cool I just have to make a note of it here.

A poster to ruby-talk wanted to create a class on demand when a user called a class method on that (non-existent-yet) class. This is how you can do it, posted by Joel VanderWerf:

class Object
   def self.const_missing(name)
     const_set(name, kl = Class.new)
     class << kl
       def method_missing(m, *args)
         puts "tried to call #{m} in #{self}"
       end
     end
     kl
   end
end

Foo.bar   # ==> tried to call bar in Foo

Note also that with this code you can now call new on any previously unknown classname, and that class as well as an instance of that class will both instantly come into existence. This is so extremely neat that I just have to use it somehow.


Back to blog