Created
July 10, 2009 22:50
-
-
Save wycats/144883 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module PythonishDecorator | |
def method_added(name) | |
return unless @decorations | |
decorations = @decorations.dup | |
@decorations = nil | |
alias_method "undecorated_#{name}", name | |
define_method(name) do |*args| | |
decorations.each {|klass| klass.call(self) } | |
send("undecorated_#{name}", *args) | |
end | |
decorations.each {|klass| klass.init(klass, name) } | |
end | |
def decorate(klass) | |
@decorations ||= [] | |
@decorations << klass | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyDecorator | |
def self.init(klass, method) | |
p [klass, method] | |
end | |
def self.call(obj) | |
p obj | |
end | |
end | |
class MyClass | |
extend PythonishDecorator | |
decorate MyDecorator | |
def omg | |
p "omg" | |
end | |
end | |
MyClass.new.omg | |
# Output: | |
# | |
# [MyDecorator, :omg] | |
# #<MyClass:0x10012a2e0> | |
# "omg" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment