DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Nic has posted 15 posts at DZone. View Full User Profile

Create Classes At Runtime

08.10.2006
| 9707 views |
  • submit to reddit
        <a href="http://drnicwilliams.com/2006/08/07/ann-dr-nics-magic-models/">Dr Nic's Magic Models</a> adds automatic ActiveRecord generation if you haven't defined a model, and for all ActiveRecords it can generate associations and validations on-the-fly based on the database schema (the table and column definitions). 

It does this with some <a href="http://drnicwilliams.com/2006/08/10/bts-magic-models-class-creation/">interesting</a> Ruby meta-programming.

For example, if you want to create a new class at runtime, and assign it a superclass, try the following:

  def create_class(class_name, superclass, &block)
    klass = Class.new superclass, &block
    Object.const_set class_name, klass
  end

With this code, you can create a class as follows:

create_class('Person', ActiveRecord::Base) do
  set_table_name :people

  def fullname
    "#{firstname} #{lastname}" # assuming the people table has firstname,lastname columns
  end
end