Sunday, September 30, 2007

Mixin and State, Any Problems?


Last week we were having a discussion about Ruby with a relative newbie who was wondering
about how Mixins and State work together.
I was sure that the discussion would be brief, explaining that all mixed in methods have full
access to its receivers state and that of course a Mixin could define initialize too.

And What About Class State?
... he said. Well, er, that is only a minor complication, I said. What exactly would you like to achieve?

We came up with a very simple, but useful, example. An Instance Tracker. It should allow us to easily
collect all instances of a class. The collected instances should than be accessible by a class method.

We decided to have some fun with TDD and specified the Tracker as follows:
  class TestInstanceTracker < Test::Unit::TestCase
def test_01_basic
a = Class::new {
include Tracker
}
a1 = a.new
assert_equal [a1], a.instances
a2 = a.new
assert_equal [a1, a2], a.instances
end # def test_01_basic
end # class TestInstanceTracker < Test::Unit::TestCase


Ok it did not take me a long time to figure it out, at first one had to assure that any new instance were added
to the instance collection, thus
  module Tracker
def initialize
self.class.instances << self
end

and than I had to labor that self.class.instances worked, therefore...
    def self.included into_a_class
into_a_class.instance_variable_set "@instances", []
class << into_a_class; attr_reader :instances end
end
end

Needless to say that code passed our testsuite (that was two assertions) brilliantly.
Now even if I had not read Kent Beck's eXtreme Programming,I had known that the testsuite was er incomplete.

As a matter of fact my collegue came up with this in no time
  def test_02_subclass
a = Class::new {
include Tracker
}
b = Class::new a
a1 = a.new
assert_equal [a1], a.instances
b1 = b.new
assert_equal [a1], a.instances
assert_equal [b1], b.instances
a2 = a.new
assert_equal [a1, a2], a.instances
assert_equal [b1], b.instances
end # def test_02_subclass

Yielding this nice little result

1) Error:
test_02_subclass(TestInstanceTracker):
NoMethodError: undefined method `<<' for nil:NilClass
./tracker2.rb:4:in `initialize'
test2.rb:24:in `new'
test2.rb:24:in `test_02_subclass'

And Subclasses?

Ok so he wants subclasses, yes sure, so would I, let us see...
As we are already telling the class we are included into to do some stuff, why not just tell it to include us
into any subclass which is created from itself

Such things can be done with the help of the class callback inherited.
  def self.included into_a_class
into_a_class.instance_variable_set "@instances", []
class << into_a_class
attr_reader :instances
def inherited by_class
by_class.send :include, Tracker
end
end
end # def self.included into_a_class

This again made the tests pass, which means that we had to come up with new tests.

And Module Inclusion?

He cannot be serious, what does he want?
Ah yes well, the following
  def test_03_includes
m = Module::new {
include Tracker
}
a = Class::new {
include m
}
b = Class::new a
a1 = a.new
assert_equal [a1], a.instances
b1 = b.new
assert_equal [a1], a.instances
assert_equal [b1], b.instances
a2 = a.new
assert_equal [a1, a2], a.instances
assert_equal [b1], b.instances
end # def test_03_includes

Actually it is pretty simple, when we are included into a class we do what we did so far:

  • Define the class instance variable

  • Define the class level accessor to the class instance variable

  • Tell the class to include us into all its subclasses via the self.inherited callback


When we are included into a module however, we have to do all the above again, that is in
  def self.included into_module
case into_module
when Module
#(1)

we have to put the exact code of the method at #(1) again.
Infinite code has some serious drawbacks though, very long development time being one that springs into mind first.

Ruby however let us define such a strange recursion without any problem:
  module Tracker
SelfIncludedProc = proc {
| into_a_module |
case into_a_module
when Class
into_a_module.instance_variable_set "@instances", []
class << into_a_module
attr_reader :instances
def inherited by_class
by_class.send :include, Tracker
end
end
when Module
class << into_a_module; self end.send :define_method, :included, &SelfIncludedProc
end # case into_a_module
}

class << self; self end.send :define_method, :included, &SelfIncludedProc

def initialize
self.class.instances << self
end
end

And that passes our tests again.

But there is one important test that does not pass:

This code just does not seem right

I thought about it a little bit and than the scales fell from my eyes, of course it is not right, I was doing two
things at the same place, coding and metacoding, so all I need to do is to tear these two parts apart.

The first and relatively uninteresting part is the application code that creates a class instance variable, its accessor and the automatic addition of new instances.

The second part is simply a kind of a Module that allows us to define class level code for
all subclasses and even via indirect inclusion.

That's what I want, I just have no idea how to call such a beast, so I called it RecModule,
great. I will accept all naming suggestions very cheerfully.



A Home Made Module Class

Let us have a look at the code:


class RecModule < Module
def recursive_included &blk
# Define a block that defines the included
inclusion = proc { | by_module |
super by_module
blk.call by_module if Class === by_module
class << by_module; self end.
send :define_method, :included, &inclusion
}
# Define included in base module
class << self; self end.
send :define_method, :included, &inclusion
end
end # class RecModule

Yep and?


Ok it will make more sense to you if we use it... but please note the repeating pattern of the way to define Module#included by means of a self referring block into our including modules.


M1 = RecModule.new {
recursive_included do |by_class|
class << by_class
attr_accessor :x
end
end
}

M2 = RecModule.new {
include M1
}
class A
include M2
end
B = Class::new A

A.x = 46
B.x = 42
p A.x # --> 46
p B.x # --> 42

I have implemented a recursive_include that will actually only execute its block for including
classes, but other similar tricks could have been used.


And Does It Really Work?


Best way to find out is to try it, I will just reimplement the InstanceTracker with the new idioms...



InstanceTracker = RecModule.new {
recursive_included do |by_class|
class << by_class
def instances
@__instances__ ||= []
end
end
end

def initialize *args, &blk
super
self.class.instances << self
end
}

M2 = RecModule.new {
include InstanceTracker
}
class A
include M2
end
B = Class::new A

A.new
B.new
A.new
p A.instances # --> [#<A:0x2b66028>, #<A:0x2b65fd8>]
p B.instances # --> [#<B:0x2b66014>]

Please note that M2 could even be a regular Module, I however think that using a RecModule reflects the intent of the code better, but that could be a matter of taste. For those who would prefer to use modules down the inclusion chain, it works perfectly too.


I am not sure that this is already the maximum I could have done in abstracting this functionality, but 14 lines of code for implementing such a basic InstanceTracker feels as about ok (10 lines would be better sigh).


There is however one thing that makes me quite nervous, I feel proud and pleased with myself about it...
Hopefully there will be some gentle reader who will tell me why I should not...

Saturday, August 18, 2007

No More Instance Variables in My Prototypes.

Last week we have seen a very simple but working implementation of the Prototype Paradigm in Pure Ruby. I have striven to implement it without orbiting too much around the classical Ruby Programming Paradigm using/ Classes and Modules. Using the exposed methods of the PPP API we can indeed forget about modules and classes at all, notwithstanding that they are doing the work behind the scenes of course.
By looking at our examples however, we see that we use instance variables for properties (or attributes) of our objects to remain in the OO jargon.
By defining attribute accessors this fact can be hidden but we can by no means avoid that instance variables are used directly to access the properties we have defined.

This week we will add a feature to the Prototype implementation that allows us to define properties without any usage of instance variables. We will define properties by means of closures, and we will allow a very simple way to define properties on a Per Object base as well as on a Per Prototype base.

Properties

Properties contain information attached to an object. In pure Ruby we use instance variables very often to represent properties. As a matter of fact we are talking about attributes and they are implemented with the well known attr_*
definitions:

class Person
attr_reader :name
attr_accessor :age
def initialize name, age=nil
@name = name
@age = age if age
end
end

spencer = Person.new "Tracy", 107
hepburn = Person.new "Katharine"

Obviously name and age are properties attached to each object and not shared amongst all objects of the same class. If we want such a beast in pure Ruby we can use Class Instance Variables1.
The classical example of such a shared property is to count instances of the class, and that is what the following code does:

class Person
attr_reader :name
attr_accessor :age
@count = 0
class << self
attr_accessor :count
end
def initialize name, age=nil
@name = name
@age = age if age
self.class.count += 1
end
end


spencer = Person.new "Tracy", 107
puts Person.count # -> 1
hepburn = Person.new "Katharine"
puts Person.count # -> 2



(1)The usage of Class Variables (starting with @@) has been discussed a lot on the Ruby-Talk ML and I adhere to a vast group of Rubyist who discourage their usage.



Can PPP do this too?

Well it can, now, but you have not seen the code yet;). Let us have a look how it is used before explaining the implementation. The code below is the equivalent to the above code but expressed in PPP.

require 'ppp'

person = new_proto {
proto_variable :count, 0
def init name, age=nil
obj_variable :name, name
obj_variable :age, age
self.count += 1
end
}

spencer = person.new "Tracy", 107
puts spencer.count # -> 1
hepburn = person.new "Katharine"
puts person.count # -> 2

There are some differences, as a matter of fact per object variables and per prototype variables are syntactically identical, please note too, that, like in Pure Ruby, you cannot assign to a prototype without an explicit receiver, hence the self.count += 1 above, the same has to be done for object variables:


person.ext_proto {
def birthday
self.age += 1
end
}


Looking under the Hood

I decided to use closures, I just dislike the @ sign I guess;)


class Object
def singleton; class << self; self end end
end

First of all I monkey-patched Object with the singleton method above, this is used very frequently by many Metaprogramming Gurus, so I need that too. Seriously you will see soon why this is useful.


class Prototype
def obj_variable varname, value, readonly = false
variable = value
singleton.instance_eval do
define_method varname do variable end
end
return if readonly
singleton.instance_eval do
define_method "#{varname}=" do | val | variable = val end
end
end # def obj_variable varname, value, readonly = false
end

Then the definition of obj_variable goes right into the Prototype class, that is why we use it in the init method and not inside the prototype block.
Please note the usage of the closure. The local variable called variable is created in the first line of the method and then we use two metaprogramming tools, instance_eval and define_method to define the accessor methods to the property. As both of these use blocks we have created a closure to access the local variable variable. Nobody can take this away from us anymore.


class Module
def proto_variable varname, value, readonly=false
variable = value
define_method varname do variable end
return if readonly
define_method "#{varname}=" do |val| variable = val end
end # def proto_variable varname, value
end # class Module

The definition of proto_variable has to go into Module of course. That is the context in which the block of new_proto or ext_proto is interpreted in.
Note the same technique as above only that we do not need the singleton here, we want the method to be defined in the prototype itself as this behavior is shared between the prototype and its objects.

Is This Good For Something?
Sure, allows me to write a Blog :). But maybe I can convince you of the Beauty and Usefulness of the PPP by means of the example of the open-proto implementation.
The open-proto implementation mimics open-struct and Facet's open-object behavior. Properties can be created on the fly:

require 'labrador/exp/open-proto'

my_open = new_proto(Prototype::OpenProto) {
def greeting
puts "I am #{name} and I have a value of #{value}"
end
}
my_object = my_open.new :name => "Fourty Two"
puts my_object.name
my_object.value = 222

another = my_object.new :name => "Fourty Six", :value => 42
my_object.greeting
another.greeting


Properties are defined on the fly, on a per object base and either by assignment or in the constructor.
It amazed myself how easy it was to implement this behavior (as it is in Pure Ruby I admit ;).

class Prototype
OpenProto = new_proto do
def init params={}
params.each_pair do |k,v|
obj_variable k, v
end
end

def method_missing name, *args, &blk
super name, *args, &blk if
args.size != 1 or
blk or
name.to_s[-1] != ?=
obj_variable name.to_s[0..-2], args.first
end
end
end

I make this 17 lines of Ruby Code.

Conclusion:

I hope you have enjoyed the journey, gentle reader, if you would like to play around with this programming style maybe you would like to have a look at Labrador as PPP and open-proto are part of version 0.1 of the Lazy Programmer's Best Friend.
I have uploaded the two files labrador/exp/ppp and labrador/exp/open-proto in an extra file called labrador-experimental-0.1 you can download all that from Rubyforge.

Saturday, August 11, 2007

And this week, Prototypes, The Conclusion

Last time I followed a path I was put on by the excellent work of Ara T. Howard, and I stopped at a very naive implementation of the Prototype Programming Paradigm. (Yet another PPP;).

It was the fast (and late) conclusion of some days of refelection and testing of ideas, it is far from ideal...
The thing that disturbes me most is that I tempted to deal with data ( c.f. Prototype#deepdup), and I did not even do it well.
Dealing with data is a bad idea anyway, we are talking behavior here, and data should not influence the conceptional decisions to be taken.

Freed from any data concerns I came up with the following code, but before throwing it at you, gentle reader, I would like to comment the concept I am following here.
In order to avoid unneccessary confusion (I will not avoid necessary confusion, those who read my posts at ruby-talk know why ;), I will use Prototype (capitalized) whenever I refer to the implementation ( a Ruby class ), and prototype (lowercase) whenever I refer to a prototyped object (an instance of Prototype as a matter of fact).

And What Is A Prototype Anyway?

A prototype is an object that has its behavior closely attached to itself. It playes the role of a class and an instance of that class at the same time.
Remember, it was the main motivation of my last post to get rid of classes at all in our programs.
I losely follow a definition of prototype as defined here.

It is the Prototype class, yes we use classes for implementation of this nevertheless ;), that will take care of gluing behavior into the prototype object.
The basic instrument to do so is the __proto__ attribute Prototype defines for its instances.
We will see shortly that __proto__ is indeed a Module that will be included into new modules replacing it as soon as a prototype will be extended with new functionality.

It is important to remember that Ara T. Howard and Pit Capitain had to do very much work (as interesting and sophisticated it was) to allow for dynamic method redefinition for class based methods.
Our classless approach rips this burden off our shoulders of course, all methods a prototype responds to are module based (via the standard Ruby extend).

Inheritance & Method Resolution Order

Inheritance is therefore implemented by method inclusion into the __proto__ attribute of a prototype.

We have a prototype p which has stored its behavior in its __proto__ attribute. This is indeed an invariant of this PPP implementation:
A prototype is always extended by the module kept in its __proto__ attribute.
Whenever we want to extend a p with some new behavior it is done via a new module, either given as a module or by constructing one on the fly from a given block.
This new module will become the value ot the p's __proto__ attribute but not before including the value of the old value of the prototype's __proto__ attribute into the module. Thus the old behavior is not lost.
The code for doing this is factorized into Prototype's private extend_one method and is simple enough:

  def extend_one mod
proto = __proto__
mod.instance_eval { include proto } if proto
self.__proto__ = mod
extend mod
end


As mentioned above the Prototype class implements an attribute __proto__. The constructor allows us to indicate behavior to be inherited as follows, a list of modules ( of whihch the last will be the last in the inheritance chain ) and an optional block of which a module will be constructed.
The module constructed from the block is the last to be inherited into the __proto__ chain.

The following example shows the method resolution order as described above.


   module A
def a; 42 end
def b; 46 end
def c; 39 end
end
module B
def b; 52 end
end
p = Prototype.new( A, B ){
def c; 60 end
}

puts p.a # --> 42
puts p.b # --> 52
puts p.c # --> 60

And here goes the definition of Prototype#initialize which does the work to arrive at the result shown above:


PrototypeError = Class::new StandardError

class Prototype
attr_accessor :__proto__
def initialize *args, &blk
ext_proto *args
ext_proto Module::new( &blk ) if blk
end # def initialize *args, &blk
...
end # class Prototype



How To Use It, The Prototype API

We want of course some simple way to create prototypes new clones or copies of a prototype or to extend prototypes.
The following interface methods can be used for this task:


class Prototype

def ext_proto *args, &blk
args.each do
| arg |
case arg
when Module
extend_one arg
else
begin
extend_one arg.__proto__
rescue NoMethodError
raise PrototypeError,
"Cannot extend an object with a non Module or non Prototype object"
end
end # case arg
end # args.each
extend_one Module::new( &blk ) if
blk or args.empty?
self
end # def ext_proto
end # class Prototype

module Kernel
def new_proto superobject=nil, *mods, &blk
begin
superobject.dup
rescue TypeError, NoMethodError
Prototype.new
end.ext_proto( *mods, &blk )
end
end # module Kernel

Thus we will be allowed to create a new prototype with


   new_proto nil, Comparable do
def <=> other
...
end
end

Or we might like to write more explicit code:



module Printable
def to_s; inspect end
end

sortable = new_proto
sortable.ext_proto Printable, Comparable do
def <=> other
name <=> other.name
end
attr_accessor :name
def init name
self.name = name
end
end

puts [sortable.new( "Vilma" ),
sortable.new( "Angie" ) ].sort
##<Prototype:0x2b64110 @name="Angie", @__proto__=#<Module:0x2b643f4>>
##<Prototype:0x2b641c4 @name="Vilma", @__proto__=#<Module:0x2b643f4>>


No More Classes! No More Modules?

Although I do not see any technical problem to use modules directly, it might be more consistent an approach not to do so anywmore.
We have got rid of class why not get rid of module too? This kind of paradigm change can do a lot to your programming style.

The alternative would be to use prototypes and anonymous module blocks exclusively (still being able to do a "include mod" in the block of course).
In this alternative way the code above would look as follows:


printable = Prototype.new {
def to_s; inspect end
}
sortable = new_proto printable, Comparable do
...

Note that we still allow modules in the inheritance chain, this seems quite useful for the usage of predefined modules.

And What About Object Initialization?
This is the last missing piece of our puzzle, Prototype defines a new method that will call an init method for the newly created object, if it exits that is of course.
Not much magic here


class Prototype
def new *args, &block
o = dup
o.extend __proto__
o.instance_eval {
init( *args, &block )
} if respond_to? :init
o
end # def new *args, &block
end # class Prototype

Please note that our only concern is to disassociate the new object from the generating prototype object. It is completely up to the user to manage the data, data can be shared between a generator object and a generated object by means of references pointed to by instance variables defined for the generator.
Example for shared data between generator prototype and generated prototype:


   printable = Prototype.new {
def to_s; inspect end
}

dog = new_proto printable do
attr_accessor :name
def init name=nil
self.name = name if name
end
end
vilma = dog.new %q{vilma}
angie = vilma.new
angie.name << "& angie"

puts vilma
puts angie
##<Prototype:0x2b64304 @__proto__=#<Module:0x2b64458>, @name="vilma& angie">
##<Prototype:0x2b6428c @__proto__=#<Module:0x2b64458>, @name="vilma& angie">


The PPP Implementation
Here goes the whole implementation:


PrototypeError = Class::new StandardError

class Prototype
attr_accessor :__proto__
def initialize *args, &blk
ext_proto *args
ext_proto Module::new( &blk ) if blk
end # def initialize *args, &blk

def ext_proto *args, &blk
args.each do
| arg |
case arg
when Module
extend_one arg
else
begin
extend_one arg.__proto__
rescue NoMethodError
raise PrototypeError,
"Cannot extend an object with a non Module or non Prototype object"
end
end # case arg
end # args.each
extend_one Module::new( &blk ) if blk or args.empty?
self
end # def ext_proto

def new *args, &block
o = dup
o.extend __proto__
o.instance_eval {
init( *args, &block )
} if respond_to? :init
o
end # def new *args, &block

private
def extend_one mod
proto = __proto__
mod.instance_eval { include proto } if proto
self.__proto__ = mod
extend mod
end
end

module Kernel
def new_proto superobject=nil, *mods, &blk
begin
superobject.dup
rescue TypeError, NoMethodError
Prototype.new
end.ext_proto( *mods, &blk )
end
end # module Kernel


Performance?

Performance is bad of course, Prototype based code is about 10 times slower than class based code, as my first benchmarks have shown.

Wednesday, August 1, 2007

Classless Ruby, a Paradigm Change?

What are classes for in Ruby?

That seems quite a stupid question at first, let us see if we can work to a point where the question makes more sense.

The whole thing started in my mind by a recent post of Ara T. Howard, implementing a neat meta-programming trick allowing to redefine methods.

Method Redefinition
The basic idea was to allow to redefine a method in a class by still having access to the redefined method via the super call.
Without looking at the implementation this is what Ara wanted to achieve.

The implementation, heavily influenced by Pit Captain, can be found here, have a look here if you are interested in Ruby Metaprogramming, it is really top notch code.

class C
def foo() 'f' end
def bar() 'b' end
def foobar() foo + bar end
end

c = C.new
p c.foobar # => "fb"

class C
redefining do
def foo() super + 'oo' end
end
end

p c.foobar # => "foob"

class C
redefining do
def bar() super + 'ar' end
end
end

p c.foobar # => "foobar"

class C
redefining do
def foo() super.reverse end
def bar() super.reverse end
end
end

p c.foobar # => "oofrab"

It is indeed a nice feature to have, a very modular inheritance mechanism. If you have looked at the implementation above, surely you have had a look at the implementation already;), you will see that it is rather complicated.
There are two reasons for that, firstly there is no way to tell Ruby to accept block parameters in a block, thus the following just will not be possible in Ruby 1.8, this will fortunately change in 1.9.


define_method( :my_method ) {
|*args, &blk|
...
}

And secondly there is a well defined behavior of directly defined methods being looked up before mixed-in methods.
When Ara published his redefining code first I had the urge to write this much, much simpler and I almost succeeded, actually I knew that the code was not doing what Ara wanted, but I felt that the simplicity of the solution was worth looking into it.
I also preferred to define the meta-code in class Module rather than in class Class.

A Naive Approach


  class Module
def redefine &blk
include Module::new( &blk )
end
end


Now this does some pretty neat tricks already, let us look at one example:
  module M
def m; 1 end
end

module N
include M
redefine do
def m; super + 1 end
end
end

class A
include N
redefine do
def m; super + 1 end
end
end

puts A.new.m # --> 3

Unfortunately we cannot redefine a method that has been declared in a class as it will be looked up first, that is why Ara and Pit went through so much trouble to save the method, remove it from the class and put it on a call stack, they did not do that (only) for fun.
In order to demonstrate it change the definition of class A as follows


  class A
def m; 41 end
redefine do
def m; super + 1 end
end
end

puts A.new.m


The deception of not getting the right answer is great of course.
But how can we get 42? Yes, of course, by using Ara's and Pit's code...
Actually I fell in love with my naive code above.
I am well aware of its limitations, but why not just continue walking on this road? We will see where that gets us.
I was quite pleased with the journey.


Mixin Rules, Or Does It Not?

The first idea to allow redefinition is simply to use redefine for the definition of the methods in the class.
This would also allow to explicitly forbid redefinition for conventional methods, the following example does not even use redefine as it is just too simple, we explicitly mix an anonymous module in.

  class Mixin
include Module::new {
attr_reader :a
def initialize a
@a = a
end
def increment
@a += 1
end
}
def old_style; "old_style" end
end # class Mixin

m = Mixin.new 46
puts m.a # --> 46
m.increment
puts m.a # --> 47
puts m.old_style # --> "old_style"

class Mixin
include Module::new {
def increment
super
@a += 2
end

def old_style
super << "::new_style"
end
}
end

m.increment
puts m.a # --> 50!!
puts m.old_style # --> "old_style"


Let us imagine, for the sake of argument, that you like this idiom, are you going to write the following code pattern forever?


class MyClass
include Module::new {
...


Probably not, why not mimic Ruby's class keyword a little bit and hide the implementation details in a Kernel method?

module Kernel
def new_style_class name, superclass=Object, &block
begin
Object.const_get( name )
rescue
Object.const_set( name, Class::new( superclass ) )
end.
instance_eval{ include Module::new( &block ) }
end
end # module Kernel

new_style_class :A do
attr_reader :value, :version
def initialize
@version=1
@value =0
end

def set_value v
@value = v
end
end

a = A.new
puts a.version
a.set_value 52
puts a.value

new_style_class :A do
def initialize
@version=2
end
end
puts A.new.version


Note that the such created new_style_class is a straight forward Ruby class that you can use and monkey patch as any other Ruby class.

Did I Say Classless?

Easy enough, let us just forget about Class.

Instead of creating the classic Ruby class and storing it in the class constant, why not just creating objects with a Kernel method, a little bit like in Javascript.

Then we extend them with our anonymous modules on the fly.

I will finish this post with some code demonstrating the usage of classless Ruby but please note how Ara's brilliant idea is still there, just look into Object#ext_object.

PrototypeError = Class::new( StandardError )
class Prototype
attr_accessor :__proto__
class << self
alias_method :orig_new, :new
def new *args, &block
o=orig_new( *args, &block )
o.__proto__ = Module::new
o
end
end

def deepdup
o = dup
instance_variables.each do |ivar|
val = instance_variable_get( ivar )
val = val.dup rescue val
o.instance_variable_set( ivar, val )
end
o
end
end # class Prototype

module Kernel
def new_object superobject=nil, &block
begin
superobject.deepdup
rescue NoMethodError
Prototype.new
end.ext_object( &block )
end
end # module Kernel

class Object
def ext_object &block
raise PrototypeError,
"Not a prototype" unless
respond_to?( :__proto__) && Module === __proto__
old_proto = __proto__
self.__proto__ = Module::new( &block )
__proto__.instance_eval{ include( old_proto ) }
extend __proto__
end

def clone &block
new_object( self, &block )
end
end # class Object

my_object = new_object {
attr_accessor :a, :b
def to_s; "#@a, #@b" end
}
my_object.a = 52
my_object.b = 60
other = my_object.clone {
def reset; @a=@b=nil end
}
puts my_object # --> 52, 60
puts other # --> 52, 60
other.reset
puts my_object # --> 52, 60
puts other # --> ,