Skip to content

Commit

Permalink
Maintain contextual methods after a method redefinition
Browse files Browse the repository at this point in the history
  • Loading branch information
Pat Maddox committed Apr 6, 2008
1 parent 46d290f commit 2f6f20d
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
19 changes: 15 additions & 4 deletions lib/context.rb
Expand Up @@ -21,26 +21,37 @@ def in_context(name, &block)
m = module_for_context(name) || Module.new
m.module_eval &block
m.instance_methods.each do |meth|
if instance_methods.include?(meth)
default_context_methods << instance_method(meth)
remove_method meth
end
add_to_default_context meth if instance_methods.include?(meth)
contextual_methods << meth
end
context_modules[name] = m
name
end

def method_added(meth)
add_to_default_context(meth) if contextual_methods.include?(meth.to_s)
end

def module_for_context(context)
context && context_modules[context]
end

def add_to_default_context(meth)
default_context_methods << instance_method(meth.to_s)
remove_method meth
end

def context_modules
@context_modules ||= { }
end

def default_context_methods
@default_context_methods ||= []
end

def contextual_methods
@contextual_methods ||= []
end
end

def self.included(klass)
Expand Down
7 changes: 7 additions & 0 deletions spec/context_spec.rb
Expand Up @@ -35,6 +35,13 @@ def called?; @called; end
lambda { @object.call }.should raise_error(NoMethodError)
end

it "should call the method in context after the instance method is redefined" do
@klass.send(:define_method, :call) { :noop }
with_context(:callable) { @object.call }
@object.should be_called
lambda { @object.call.should == :noop }
end

describe "when the context is opened again" do
it "should redefine the method" do
@klass.in_context(:callable) { def call; :redefined; end }
Expand Down

0 comments on commit 2f6f20d

Please sign in to comment.