Skip to content

Instantly share code, notes, and snippets.

@markryall
Created September 16, 2010 08:07
Show Gist options
  • Save markryall/582122 to your computer and use it in GitHub Desktop.
Save markryall/582122 to your computer and use it in GitHub Desktop.
module Things
class Thing
instance_methods.each { |m| undef_method m unless m =~ /^__/ or ['instance_eval'].include?(m) }
include Things
def initialize
@hash = {}
end
def __hash
@hash
end
def method_missing meth, *args, &block
if meth.to_s =~ /^(.+)=$/
@hash[$1.to_sym] = args.first
else
if block
@hash[meth] = thing &block
else
@hash[meth] = args.first if args.first
@hash[meth]
end
end
end
end
def thing &block
thing = Thing.new
thing.instance_eval &block if block_given?
thing
end
end
require File.dirname(__FILE__)+'/spec_helper'
require 'things'
describe "a thing" do
include Things
it "should initially return nil for any method" do
thing.qwerty.should be_nil
end
it "should allow arbitrary values to be assigned with setter" do
t = thing
t.qwerty = 4
t.qwerty.should == 4
end
it "should allow arbitrary values to be assigned with method call" do
t = thing
t.qwerty 4
t.qwerty.should == 4
end
it "should allow arbitrary values to be assigned in thing block" do
t = thing {
qwerty 4
}
t.qwerty.should == 4
end
it "should allow nested things to be assigned by using thing method" do
t = thing {
qwerty __thing {
asdf 4
}
}
t.qwerty.asdf.should == 4
end
it "should allow nested things to be assigned by passing block" do
t = thing {
qwerty {
asdf 4
}
}
t.qwerty.asdf.should == 4
end
it "should expose hash so it is possible to find out about things" do
t = thing {
qwerty {
asdf 4
}
}
t.__hash.keys.should == [:qwerty]
t.qwerty.__hash.keys.should == [:asdf]
end
it "should handle references in block" do
q = thing {
asdf 4
}
t = thing {
q2 = qwerty q
qwerty2 q2
}
t.qwerty.asdf.should == 4
t.qwerty2.asdf.should == 4
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment