Created
June 12, 2009 21:00
-
-
Save Peeja/128916 to your computer and use it in GitHub Desktop.
Using bindings instead of alias_method_chain.
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
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