Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Ruby fun: a one time method override.
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
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