Morphing an object among peer subclasses


i’m trying to find the best way to swap an object among subclasses. The
use case is changing among graph types (ex:

the models are

BarGraph < Graph
LineGraph < Graph
ScatterGraph < Graph
class Graph < ActiveRecord::Base
def change_type_to(target_type)
graph.update_attributes :type =>

so our code today looks like this

graph = BarGraph.create!

change the graph from a bar graph to a line graph

new_graph = graph.change_type_to LineGraph
assert_equal LineGraph, new_graph.class # passes

#I would like to DRY it up a bit to look like this:
graph.change_type_to! LineGraph
assert_equal LineGraph, graph.class

I have also played with a separate GraphMorpher with a class method to
do this, but it felt too clunky.

It seems impossible to me. But this is ruby. Is there way? Or a
better way to approach the whole use case?


sorry Graph#change_type_to

should be:

def change_type_to(target_type)
self.update_attributes :type =>