Search code examples
rubyinheritancedynamicmetaprogrammingdynamic-class-loaders

Ruby Generating Subclass at runtime


I am facing a problem right now.

I have one parent class Item (Model). I have two static subclasses inheriting from Item.

But through the view form, I want admin users to be able to create a new Item subclass as well at run time.

class Item < ActiveRecord::Base
 #template methods
end

class StoreItem < Item
 #hooks for overriding template method
end

class OnlineItem < Item
 #hooks for overriding template method
end

In the view, I want to give a form where users can add a new name and click create and it creates a new class dynamically.

I want help with respect to:

  1. How to achieve this.
  2. Also is it metaprogramming or I have to use a factory pattern and give a default class?

Solution

  • Do you look for `Class.new(Item)``

    Example:

    require 'active_record'
    
    class Item < ActiveRecord::Base
     #template methods
    end
    
    x = Class.new(Item)
    puts x.ancestors
    

    One of the ancestors is Item.

    By the way: Your Class StoreItem < Item is wrong. You must use class instead of Class in this case.