Skip to content

Instantly share code, notes, and snippets.

@nixpulvis
Last active December 18, 2015 16:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nixpulvis/5811931 to your computer and use it in GitHub Desktop.
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!`.
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