Lightweight method wrapper in Ruby.
alias_method_chain alternative. How easy to wrap a new feature around existing methods with method_wrapper.
gem install method_wrapper
-
Wrap multi methods to a feature in a line.
-
Be able to call wrap_methods before methods defined.
-
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.
require 'method_wrapper' 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"