Define and alias
Published May 8, 2009
in Ruby
I got tired of the redundancy in the alias_method_chain pattern. Generally, one does
def my_method_with_the_feature(argument1, *remaining_arguments) ... end alias_method_chain :my_method, :the_feature
But why should I have to tell ruby the method name and feature twice? With this extension to Module,
class Module def define_and_alias(target, feature, &blk) aliased_target, punctuation = target.to_s.sub(/([?!=])$/, ''), $1 define_method :"#{aliased_target}_with_#{feature}#{punctuation}", &blk alias_method_chain target, feature end end
You can just do
define_and_alias :my_method, :the_feature do |argument1, *remaining_arguments| ... end
And all was well and DRY.