Creating Classes at Runtime

So far, you have modified classes and created new objects from existing classes. But how would you go about creating a completely new class at runtime? Well, just as you can use const_get to access an existing class, you can use const_set to create a new class. Here’s an example of how to prompt the user for the name of a new class before creating that class, adding a method (myname) to it, creating an instance (x) of that class, and calling its myname method:

create_class.rb

puts("What shall we call this class? ")
className = gets.strip().capitalize()
Object.const_set(className,Class.new)
puts("I'll give it a method called 'myname'" )
className = Object.const_get(className)
className::module_eval{ define_method(:myname){
        puts("The name of my class is '#{self.class}'" ) }
    }

x = className.new
x.myname

If you run this program and enter Xxx when prompted for the name of a new class, the code will use const_set to create the constant Xxx as a new class; then module_eval is called on this class, and define_method is used to create a method whose name matches the symbol :myname and whose contents are given by the code in the curly brace-delimited block; here this happens to be a single puts statement that displays the class name.

Run this code, and enter Xxx when prompted. An object, x, is created from the Xxx class; its myname() method is called; and, sure enough, it displays the class name:

The name of my class is 'Xxx'
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.166.149