Last active
December 13, 2015 18:58
-
-
Save TikiTDO/4958797 to your computer and use it in GitHub Desktop.
Alias methods, but add some static arguments before or after the call
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Usage: | |
# class Thing | |
# def method_name(*args) | |
# args | |
# end | |
# alias_shift_arg(:method_changed, :method_name, 1, 2, 3) | |
# end | |
# thing = Thing.new | |
# thing.method_name("a").inspect #=> ["a"] | |
# thing.method_changed("a").inspect #=> [1, 2, 3, "a"] | |
class Object | |
class << self | |
# Register an alias before the method is defined. Not for performance critical use | |
def alias_preload(target, source) | |
self.send(:define_method, target) do |*orig_args, &block| | |
self.send(source, *orig_args, &block) | |
end | |
end | |
# Register a method that appends some arguments before calling the aliased method | |
def alias_push_arg(target, source, *args) | |
self.send(:define_method, target) do |*orig_args, &block| | |
self.send(source, *(orig_args + args), &block) | |
end | |
end | |
# Register a method that prepends some arguments before calling the aliased method | |
def alias_shift_arg(target, source, *args) | |
self.send(:define_method, target) do |*orig_args, &block| | |
self.send(source, *(args + orig_args), &block) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment