This post originated from an RSS feed registered with Ruby Buzz
by Michael Neumann.
Original Post: Implementing Python Decorators in Ruby (Part II)
Feed Title: Mike's Weblog
Feed URL: http://www.ntecs.de/blog-old/index.rss?cat=ruby&count=7
Feed Description: Blogging about Ruby and other interesting stuff.
In Part I of the article, I
hacked the Ruby interpreter and modified one single line to implement
Python Decorators in Ruby. Now I'll show some more examples in both Python
and Ruby.
The examples are taken from the article Decorate
this.
Now the same example in Ruby (with my single-line patch applied):
def wrapwith(obj, method_id)
old_method = method(method_id)
new_method = proc {|*args|
print "##", obj, "\n"
old_method.call(*args)
}
self.class.send(:define_method, method_id, new_method)
end
wrapwith 42,
def f(x) x*2 end
# let's use it
print f(4)
For me, the Python example is harder to understand, as three nested
function definitions are involved. Now, the Ruby example is just fine, but
in Ruby 2.0 we can even do better:
def f(x) x*2 end
def wrap:f(x)
print "##", 42, "\n"
super # calls "f"
end
print f(4)
For all examples, the output will be:
## 42
8
Prototype-based OO
Below, I only show how to apply prototype-based OO with Decorators in
Python, not how to implement it. For the complete Python example see Decorate
this.
class Foo
def initialize
@x = 42
end
end
foo = Foo.new
def foo.print_x
print @x
end
foo.print_x # => 42
Note that the Ruby example is complete whereas in the Python example the
implementation of @addto is missing. But what if you want to add a whole
bunch of methods to an object? In Ruby it's as easy:
foo = Foo.new
class << foo
def m1
1
end
def m2
2
end
end
foo.m1 # => 1
foo.m2 # => 2