Permalink
Browse files

You can add to methods in a context

  • Loading branch information...
1 parent 527dd35 commit 46d290fdd8181f93a7e0f734643c7c45eceeeeea Pat Maddox committed Apr 6, 2008
Showing with 39 additions and 30 deletions.
  1. +6 −2 lib/context.rb
  2. +33 −28 spec/context_spec.rb
View
@@ -13,12 +13,12 @@ def method_missing(method_name, *args, &block)
end
def module_for_context(context)
- context && self.class.context_modules[context]
+ self.class.module_for_context context
end
module ClassMethods
def in_context(name, &block)
- m = Module.new
+ m = module_for_context(name) || Module.new
m.module_eval &block
m.instance_methods.each do |meth|
if instance_methods.include?(meth)
@@ -30,6 +30,10 @@ def in_context(name, &block)
name
end
+ def module_for_context(context)
+ context && context_modules[context]
+ end
+
def context_modules
@context_modules ||= { }
end
View
@@ -6,23 +6,18 @@
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
+ @klass = Class.new do
+ include InContext
+ in_context :callable do
+ def call
+ @called = true
+ end
+ end
+ def called?; @called; end
+ end
+ @object = @klass.new
@object.should_not be_called
end
@@ -39,27 +34,37 @@ def called?
with_context(:callable) { @object.call }
lambda { @object.call }.should raise_error(NoMethodError)
end
+
+ describe "when the context is opened again" do
+ it "should redefine the method" do
+ @klass.in_context(:callable) { def call; :redefined; end }
+ with_context(:callable) { @object.call.should == :redefined }
+ end
+
+ it "should define other methods" do
+ @klass.in_context(:callable) { def other; :other; end }
+ with_context(:callable) {
+ @object.call
+ @object.other.should == :other
+ }
+ @object.should be_called
+ end
+ end
end
describe "An object with an instance method, and the same method declared in a context" do
include InContext::WithContext
- class OverrideInContext
- include InContext
-
- def the_context(collector)
- collector << :instance
- end
-
- in_context(:override) do
- def the_context(collector)
- collector << :singleton
+ before(:each) do
+ @klass = Class.new do
+ include InContext
+ def the_context(collector); collector << :instance; end
+ in_context(:override) do
+ def the_context(collector); collector << :singleton; end
end
end
- end
- before(:each) do
- @object = OverrideInContext.new
+ @object = @klass.new
@collector = []
end

0 comments on commit 46d290f

Please sign in to comment.