Created
April 9, 2009 18:37
-
-
Save stefanoc/92657 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 Decorating | |
def decorate(meth_id, *modules) | |
alias_method("__#{meth_id}__", meth_id) | |
define_method(meth_id) do |*args| | |
result = send("__#{meth_id}__", *args) | |
modules.each { |m| result.extend(m) } | |
return result | |
end | |
end | |
def ddef(meth_id, *mods, &block) | |
define_method(meth_id) do |*args| | |
result = block.call(*args) | |
mods.each { |m| result.extend(m) } | |
return result | |
end | |
end | |
end | |
Object.send(:include, Decorating) | |
module Summable | |
def sum | |
inject(0) { |s, e| s + e } | |
end | |
end | |
module Title | |
def titleize | |
downcase.gsub(/\s+/, "-").gsub(/[^a-z0-9-]/, "") | |
end | |
end | |
class Account | |
ddef(:balances, Summable) do |*args| | |
[1, 2, 3] | |
end | |
end | |
class Movie | |
def title | |
"It's A Wonderful Life" | |
end | |
decorate :title, Title | |
end | |
acct = Account.new | |
puts acct.balances.sum | |
movie = Movie.new | |
puts movie.title.titleize |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment