i'm trying to find the best way to swap an object among subclasses. The use case is changing among graph types (ex: http://swivel.com/graphs/edit/5148997) # the models are BarGraph < Graph LineGraph < Graph ScatterGraph < Graph class Graph < ActiveRecord::Base def change_type_to(target_type) graph.update_attributes :type => target_type.name Graph.find graph.id end end # 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?
on 2007-02-10 03:42
on 2007-02-10 03:44
sorry Graph#change_type_to should be: def change_type_to(target_type) self.update_attributes :type => target_type.name Graph.find self.id end