Last active
December 18, 2015 16:29
-
-
Save nixpulvis/5811931 to your computer and use it in GitHub Desktop.
Dynamically alias methods and add functionality onto the end of them. Great for creating methods in rails that call `save!`.
This file contains 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
module AliasMethodizer | |
private | |
def alias_method(alias_name, name, &function) | |
define_method alias_name, -> (*args, &block) do | |
value = method(name)[*args, &block] | |
instance_exec &function if block_given? | |
value | |
end | |
end | |
end | |
class Foo | |
extend AliasMethodizer | |
def bar(x, y) | |
p yield + x + y | |
end | |
def foo(x, y, &block) | |
r = x + y | |
block.call(r) | |
end | |
alias_method(:foo!, :foo) { bar(2, 3) { 1 } } | |
end | |
puts 'original' | |
p Foo.new.foo(1, 2) { |r| p r } | |
puts 'aliasized' | |
p Foo.new.foo!(1, 2) { |r| p r } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment