Skip to content

Instantly share code, notes, and snippets.

@euge
Last active August 29, 2015 14:06
Show Gist options
  • Save euge/cb418632c7e829ed9b12 to your computer and use it in GitHub Desktop.
Save euge/cb418632c7e829ed9b12 to your computer and use it in GitHub Desktop.
module Decorator
def decorate(decorator_name, &block)
(class << self; self; end).class_eval do
define_method(decorator_name) do |method_name_to_decorate|
with_feature = "#{method_name_to_decorate}_with_#{decorator_name}"
without_feature = "#{method_name_to_decorate}_without_#{decorator_name}"
define_method with_feature do
# call decorator code passing argument of a proc that will call original method
block.call(proc { send without_feature })
end
alias_method without_feature, method_name_to_decorate
alias_method method_name_to_decorate, with_feature
method_name_to_decorate
end
end
end
end
class Monkey
extend Decorator
decorate :amazing do |orig|
puts "amazing start"
orig.call
puts "amazing end"
end
decorate :extra_cool do |orig|
puts "extra_cool start"
orig.call
puts "extra_cool end"
end
decorate :super_safe! do |orig|
begin
orig.call
rescue => ex
puts "Swallowed exception #{ex.message}"
end
end
# super_safe! \
amazing \
extra_cool \
def haha
puts "HIIII"
# raise "I am raising!"
end
end
puts "---------------"
puts Monkey.new.haha
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment