views:

92

answers:

3

Let's say I am using a STI pattern to persist several different subclasses of "Transaction," which subclasses "ActiveRecord"

My subclasses might include "HighPriorityTransaction" and "LowPriorityTransaction" which rails will store in the table "transactions" with a "type" column. Each subclass has a different implementation of the before_save callback.

My question in how can I create instances of these classes by their type string value?

I am thinking that I would get the type from a combobox, instantiate that type, and let the object handle the before_save callback through polymorphism. Any additional ideas on this would be appreciated as well.

Thanks!

A: 

I found one solution I thought I would share:

type = Kernel.const_get("type_string") 

#which in this case might be 
#type = Kernel.const_get("HighPriorityTransaction")

transaction = type.new
Lee
A: 

One problem with that approach is that it allows a client to cause any class in your application to be instantiated if they happen to know its name, unless you explicitly guard against that in your controller. Following is one alternative that could work. It creates a "registry" attribute on the Transaction class that maps subclass names to subclass objects.

class Transaction

  class << self
    attr_reader :registry

    def inherited(sub)
      @registry ||= {}
      @registry[sub.name] = sub
    end
  end
end

class HighPriorityTransaction < Transaction; end

Transaction.registry["HighPriorityTransaction"].new.class # HighPriorityTransaction
Greg Campbell
A: 

This might be along the lines of what you're looking for:

@transaction = "HighPriorityTransaction".camelize.constantize.new

KarenG