Forum: Ruby on Rails morphing an object among peer subclasses

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Brian M. (Guest)
on 2007-02-10 03:42
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?
Brian M. (Guest)
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
This topic is locked and can not be replied to.