Skip to content

Instantly share code, notes, and snippets.

@nakajima
Created October 3, 2008 08:03
Show Gist options
  • Save nakajima/14528 to your computer and use it in GitHub Desktop.
Save nakajima/14528 to your computer and use it in GitHub Desktop.
Shoot footing fun, ported from JavaScript
require 'rubygems'
require 'metaid' # always a good idea
require 'spec'
Object.class_eval do
def with(hash)
hash.each do |key, value|
meta_def(key) { hash[key] }
meta_def("#{key}=") { |v| hash[key] = v }
end
return unless block_given?
result = yield
hash.each do |key, value|
meta_eval { remove_method(key) }
meta_eval { remove_method("#{key}=") }
end
result
end
end
describe "with" do
def ok; :out end
before(:each) do
@hash = { :foo => :bar, :ok => :in }
end
it "should just define methods when no block given" do
with({ :fizz => :buzz })
fizz.should == :buzz
end
it "should make hash keys available in context" do
with(@hash) { foo }.should == :bar
end
it "should remove methods outside with context" do
with(@hash) { foo }
proc { foo }.should raise_error
end
it "should preserve other defined methods" do
ok.should == :out
with(@hash) { ok }.should == :in
ok.should == :out
end
it "should allow setters" do
@hash[:foo].should == :bar
with(@hash) { self.foo = :set }
@hash[:foo].should == :set
end
it "should remove setters" do
with(@hash) { foo }
proc { self.foo = :set }.should raise_error
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment