Permalink
Browse files

first context stuff

  • Loading branch information...
0 parents commit 0768cdfa46c29f189c8523c66e60462f6772e666 @patmaddox committed Apr 6, 2008
Showing with 95 additions and 0 deletions.
  1. +3 −0 .gitmodules
  2. +49 −0 lib/context.rb
  3. +37 −0 spec/context_spec.rb
  4. +5 −0 spec/spec_helper.rb
  5. +1 −0 spec/vendor/rspec
@@ -0,0 +1,3 @@
+[submodule "spec/vendor/rspec"]
+ path = spec/vendor/rspec
+ url = git@github.com:dchelimsky/rspec.git
@@ -0,0 +1,49 @@
+require "singleton"
+
+module InContext
+ def method_missing(method_name, *args, &block)
+ if m = module_for_context(InContext::ContextHolder.instance.current_context)
+ (class << self; self; end).send :include, m
+ return send(method_name, *args, &block)
+ end
+ super
+ end
+
+ def module_for_context(context)
+ context && self.class.context_modules[context]
+ end
+
+ module ClassMethods
+ def in_context(name, &block)
+ m = Module.new
+ m.module_eval &block
+ context_modules[name] = m
+ name
+ end
+
+ def context_modules
+ @context_modules ||= { }
+ end
+ end
+
+ def self.included(klass)
+ klass.extend ClassMethods
+ end
+
+ module WithContext
+ def with_context(name, &block)
+ InContext::ContextHolder.instance.with_context name, &block
+ end
+ end
+
+ class ContextHolder
+ include Singleton
+ attr_reader :current_context
+
+ def with_context(name, &block)
+ @current_context = name
+ block.call if block
+ @current_context = nil
+ end
+ end
+end
@@ -0,0 +1,37 @@
+require "rubygems"
+require "expand_path"
+$:.unshift __FILE__.expand_path
+require "spec_helper"
+require "context"
+
+describe "An object with a method declared in a context" do
+ include InContext::WithContext
+
+ class ContextualObject
+ include InContext
+
+ in_context :callable do
+ def call
+ @called = true
+ end
+ end
+
+ def called?
+ @called
+ end
+ end
+
+ before(:each) do
+ @object = ContextualObject.new
+ @object.should_not be_called
+ end
+
+ it "should not respond to the method" do
+ lambda { @object.call }.should raise_error(NoMethodError)
+ end
+
+ it "should respond to the method in a context" do
+ with_context(:callable) { @object.call }
+ @object.should be_called
+ end
+end
@@ -0,0 +1,5 @@
+require "rubygems"
+require "expand_path"
+$:.unshift __FILE__.expand_path("/spec/vendor/rspec/lib")
+require "spec"
+$:.unshift __FILE__.expand_path("../lib")
Submodule rspec added at eefc5c

0 comments on commit 0768cdf

Please sign in to comment.