Method Wrapper
Lightweight method wrapper in Ruby.
Introduction
alias_method_chain alternative. How easy to wrap new features around existing methods with method_wrapper.
Installation
gem install method_wrapper
Examples
-
Wrap multi methods to a feature in a line.
-
Be able to call wrap_methods before methods defined. require ‘method_wrapper’
-
Call original method(origin_method_name). Note: I take different style from alias_method_chain because we don’t want users to know what feature has been wrapped.
Examples
class Klass
include MethodWrapper
wrap_methods [:save!, :query] => :log
def save!
"save"
end
def query
"update"
end
def save_with_log!
origin_save! + " with log"
end
def query_with_log
origin_query! + " with log"
end
end
obj = Klass.new
obj.save!
=> "save with log"
obj.origin_save!
=> "save"
You can also open the existing classes to wrap methods. Note: Be careful, you know what you are doing.
require 'method_wrapper'
class String
include MethodWrapper
wrap_methods :reverse => :upcase
def reverse_with_upcase
origin_reverse.upcase
end
end
"nuhhc gnanmas".reverse
=> SAMNANG CHHUN