Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Maintain contextual methods after a method redefinition

  • Loading branch information...
commit 2f6f20d7d721f72ee8a2f0def43b9cdd414d6e7e 1 parent 46d290f
Pat Maddox authored

Showing 2 changed files with 22 additions and 4 deletions. Show diff stats Hide diff stats

  1. +15 4 lib/context.rb
  2. +7 0 spec/context_spec.rb
19 lib/context.rb
@@ -21,19 +21,26 @@ def in_context(name, &block)
21 21 m = module_for_context(name) || Module.new
22 22 m.module_eval &block
23 23 m.instance_methods.each do |meth|
24   - if instance_methods.include?(meth)
25   - default_context_methods << instance_method(meth)
26   - remove_method meth
27   - end
  24 + add_to_default_context meth if instance_methods.include?(meth)
  25 + contextual_methods << meth
28 26 end
29 27 context_modules[name] = m
30 28 name
31 29 end
32 30
  31 + def method_added(meth)
  32 + add_to_default_context(meth) if contextual_methods.include?(meth.to_s)
  33 + end
  34 +
33 35 def module_for_context(context)
34 36 context && context_modules[context]
35 37 end
36 38
  39 + def add_to_default_context(meth)
  40 + default_context_methods << instance_method(meth.to_s)
  41 + remove_method meth
  42 + end
  43 +
37 44 def context_modules
38 45 @context_modules ||= { }
39 46 end
@@ -41,6 +48,10 @@ def context_modules
41 48 def default_context_methods
42 49 @default_context_methods ||= []
43 50 end
  51 +
  52 + def contextual_methods
  53 + @contextual_methods ||= []
  54 + end
44 55 end
45 56
46 57 def self.included(klass)
7 spec/context_spec.rb
@@ -35,6 +35,13 @@ def called?; @called; end
35 35 lambda { @object.call }.should raise_error(NoMethodError)
36 36 end
37 37
  38 + it "should call the method in context after the instance method is redefined" do
  39 + @klass.send(:define_method, :call) { :noop }
  40 + with_context(:callable) { @object.call }
  41 + @object.should be_called
  42 + lambda { @object.call.should == :noop }
  43 + end
  44 +
38 45 describe "when the context is opened again" do
39 46 it "should redefine the method" do
40 47 @klass.in_context(:callable) { def call; :redefined; end }

0 comments on commit 2f6f20d

Please sign in to comment.
Something went wrong with that request. Please try again.