Skip to content

Instantly share code, notes, and snippets.

@bradleybuda
Created October 29, 2009 21:42
Show Gist options
  • Select an option

  • Save bradleybuda/221877 to your computer and use it in GitHub Desktop.

Select an option

Save bradleybuda/221877 to your computer and use it in GitHub Desktop.
Ruby Class Redefinition
class Foo #v1
def initialize(value)
@value = value
end
def add
37 + @value
end
end
# create a Foo and serialize it
@foo_v1_instance = Foo.new(9)
@foo_instance_marshalled = Marshal.dump(@foo_v1_instance)
# redefine Foo, but save the old version in an instance var
@foo_v1 = Object.send(:remove_const, :Foo)
class Foo #v2
def initialize
@value = value
end
def mult
37 * @value
end
end
# create a Foo of the new version by unmarshalling the old version instance
@foo_v2_instance = Marshal.load(StringIO.new(@foo_instance_marshalled))
# undefine Foo
@foo_v2 = Object.send(:remove_const, :Foo)
# redefine Foo v1 without any source code
Object.send(:const_set, 'Foo', @foo_v1)
# resurrect our original Foo instance with the old Foo code base
@foo_v1_instance_reborn = Marshal.load(StringIO.new(@foo_instance_marshalled))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment