Skip to content

Instantly share code, notes, and snippets.

@thumblemonks
Created October 27, 2009 03:24
Show Gist options
  • Save thumblemonks/219271 to your computer and use it in GitHub Desktop.
Save thumblemonks/219271 to your computer and use it in GitHub Desktop.
#
# magical binding
#
module RiotA
module AssertionMacros
# def equals(expected) puts "yay"; end
def equals(expected) true; end
end
class Assertion
include AssertionMacros
attr_reader :name, :actual
def initialize(name, actual)
@name, @actual = name, actual
end
end
class Context
def initialize(name, &context_block) @context_block = context_block; end
def run; @context_block.call; end
end
module ContextMacros
def asserts(name, &test_block) Assertion.new(name, test_block.call); end
end
def self.context(name, &block)
asserts_m = Object.instance_method(:asserts)
ctx = Context.new(name, &block)
asserts_m.bind(ctx)
ctx.run
end
end
class Object
include RiotA::ContextMacros
end
#
# instance eval
#
module RiotB
class Situation
end
module AssertionMacros
# def equals(expected) puts "aya"; end
def equals(expected) true; end
end
class Assertion
include AssertionMacros
attr_reader :name, :actual
def initialize(name, sitution, &actual_block)
@name, @actual = name, instance_eval(&actual_block)
end
end
class Context
def initialize(name, &context_block)
@situation = Situation.new
instance_eval(&context_block)
end
def asserts(name, &test_block) Assertion.new(name, @situation, &test_block); end
end
def self.context(name, &block)
ctx = Context.new(name, &block)
end
end
#
# Bench
#
n = 100_000
require 'benchmark'
Benchmark.bmbm do |x|
x.report("Magical binding") do
n.times do
RiotA.context "foo" do
asserts("something") { "foo" }.equals("bar")
end
end
end
x.report("Instance eval (current)") do
n.times do
RiotB.context "foo" do
asserts("something") { "foo" }.equals("bar")
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment