Ruby fun: a one time method override.
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 'minitest/spec' | |
require 'minitest/autorun' | |
class String | |
def one_time_override(method, &override) | |
self.instance_eval do | |
def to_s | |
self.instance_eval do | |
def to_s | |
'foo' | |
end | |
end | |
'bar' | |
end | |
end | |
end | |
end | |
describe String do | |
it "should allow a one-time override of a method" do | |
foo = 'foo' | |
foo.to_s.must_equal 'foo' | |
foo.one_time_override(:to_s) { 'bar' } | |
foo.to_s.must_equal 'bar' | |
foo.to_s.must_equal 'foo' | |
end | |
end |
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 'minitest/spec' | |
require 'minitest/autorun' | |
class String | |
def one_time_override(method) | |
@original = self.method(method) | |
self.instance_eval(%Q|def #{method.to_s}; return @original.call if @called; @called = true; "#{yield}"; end|) | |
end | |
end | |
describe String do | |
it "should allow a one-time override of the to_s method" do | |
foo = 'foo' | |
foo.to_s.must_equal 'foo' | |
foo.one_time_override(:to_s) { 'bar' } | |
foo.to_s.must_equal 'bar' | |
foo.to_s.must_equal 'foo' | |
end | |
it "should allow a one-time override of the downcase method" do | |
foo = 'Foo' | |
foo.downcase.must_equal 'foo' | |
foo.one_time_override(:downcase) { foo.upcase } | |
foo.downcase.must_equal 'FOO' | |
foo.downcase.must_equal 'foo' | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment