Skip to content

Instantly share code, notes, and snippets.

@stefanoc
Created April 9, 2009 18:37
Show Gist options
  • Save stefanoc/92657 to your computer and use it in GitHub Desktop.
Save stefanoc/92657 to your computer and use it in GitHub Desktop.
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