I've been using ruby for about 8 months now and I've come to appreciate
its powerful features. But I miss python's decorators, so I made
something similar.

The code is attached; here are some examples. It's really easy to use a
decorator:

class C
  memoized
  def tak(x, y, z)
    return z if x <= y
    tak(tak(x - 1, y, z), tak(y - 1, z, x), tak(z - 1, x, y))
  end
end

And really easy to write one:

class Module
  decorator
  def memoized(name, f)
    lambda do |*args|
      ((@__memo_cache ||= {})[[name, args]] ||=
[f.bind(self).call(*args)])[0]
    end
  end
end

You can use this to do all of the usual decorator things, like
memoization, method call tracing, synchronization, currying, type
checking, basic profiling, print warnings for deprecated methods, or
anything else you can think of.

One important limitation of this implementation is that you cannot
"stack" decorators like you can in python. That's fixable, and hopefully
I'll have time to make another version of this library with stackable
decorators. But until then, maybe someone will find this useful.

I'd love to hear feedback about this library! If you have any comments
or questions, please let me know.

kr

Attachments:
http://www.ruby-forum.com/attachment/52/deco.rb

-- 
Posted via http://www.ruby-forum.com/.