Copying Classes

Posted by Paul Ingles
Thursday, November 15, 2007 20:02:00 GMT

From across the desk, George asks “can you copy classes in Ruby?”. We talk about it quickly and reason that since everything’s an Object (even classes), you probably can. Since the constant isn’t changed or duplicated (you’re essentially assigning a new one) then it ought to be possible.

Turns out it is!

class First
  def initialize
    @value = 99
  end

  def say_value
    @value
  end
end
First.new.say_value # => 99

Second = First.clone
Second.class_eval do
  define_method :say_value do
    @value + 100
  end
end
Second.new.say_value # => 199

Neat.

I’m not sure quite why you would want to clone a class to take advantage of re-use - rather than extract to a module (and share the implementation that way) or, if there’s a strong relationship that doesn’t violate the LSP etc. then look for some kind of inheritance-based design.

But, I guess you could work some kind of cool ultra-dynamic super-meta system from it. Perhaps someone with way more of a Ruby-thinking brain than me could offer some thoughts?

Comments

Leave a response

  1. Brian MitchellNovember 15, 2007 @ 09:58 PM

    How about writing it like a prototype object system would:

    Proto = Object.clone def Proto.clone; Class.new(self) end

    First = Proto.clone def First.value 42 end def First.say_value puts value end

    Second = First.clone def Second.value 100 end

    Second.say_value #=> 100

    def First.say_value puts value * 2 end

    Second.say_value #=> 200

  2. Brian MitchellNovember 15, 2007 @ 10:00 PM

    Oops. Formatting messed up a little there. I’m sure you can insert the new lines where necessary.

  3. Bill SixNovember 15, 2007 @ 10:18 PM

    Wikipedia has some pros and cons of prototype-based programming

    http://en.wikipedia.org/wiki/Prototype-based_programming

  4. Pat MaddoxNovember 21, 2007 @ 12:10 PM

    I actually found a use for it very quickly…it easily solved a problem that’s been killing me for months:

    http://evang.eli.st/blog/2007/11/21/test-your-crazy-awesome-plugins-by-cloning-classes

    Thanks a ton.