Skip to content

Instantly share code, notes, and snippets.

@sdball
Created January 25, 2013 15:02
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 sdball/4635053 to your computer and use it in GitHub Desktop.
Save sdball/4635053 to your computer and use it in GitHub Desktop.
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