Skip to content

Instantly share code, notes, and snippets.

@Peeja
Created June 12, 2009 21:00
Show Gist options
  • Save Peeja/128916 to your computer and use it in GitHub Desktop.
Save Peeja/128916 to your computer and use it in GitHub Desktop.
Using bindings instead of alias_method_chain.
require 'rubygems'
require 'activesupport'
# Let's say there's some Widget class.
class Widget
def sproing
[:original]
end
end
# We can use alias_method_chain to wrap that behavior...
class Widget
def sproing_with_amc
sproing_without_amc + [:amc]
end
alias_method_chain :sproing, :amc
end
# ...or we can use a binding.
class Widget
original_sproing = Widget.instance_method(:sproing)
define_method(:sproing) do
original_sproing.bind(self).call + [:binding]
end
end
# Note that original_sproing is a local variable. Its scope
# ends with the end of that class declaration. The reference
# to it here would raise a NameError.
#
# class Widget
# puts original_sproing
# end
require 'spec'
describe Widget, "#sproing" do
it "calls the original implementation" do
Widget.new.sproing.should include(:original)
end
it "calls the alias_method_chain implementation" do
Widget.new.sproing.should include(:amc)
end
it "calls the binding implementation" do
Widget.new.sproing.should include(:binding)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment