Permalink
Browse files

Added with_attr!.

  • Loading branch information...
1 parent 1032470 commit 91ac2a0c608732349099c2427a0090c45394b57d @kstephens committed Apr 12, 2012
Showing with 27 additions and 0 deletions.
  1. +19 −0 lib/asir/thread_variable.rb
  2. +8 −0 spec/thread_variable_spec.rb
@@ -7,10 +7,29 @@ module ThreadVariable
def self.included target
super
target.instance_eval do
+ include CommonMethods
+ extend CommonMethods
extend ModuleMethods
end
end
+ def self.setter sym
+ SETTER[sym] ||= :"#{sym}="
+ end
+ SETTER = { }
+
+ module CommonMethods
+ # Yields to block while self.name = value.
+ # Restores self.name after yield.
+ def with_attr! name, value
+ save_value = send(name)
+ send(ThreadVariable.setter(name), value)
+ yield
+ ensure
+ send(ThreadVariable.setter(name), save_value)
+ end
+ end
+
module ModuleMethods
# Defines a Module or Class attribute stored in Thread.current.
def mattr_accessor_thread *names
@@ -24,6 +24,10 @@ def ti
tc.tv1.should == nil
tc.tv1 = 1
tc.tv1.should == 1
+ tc.with_attr! :tv1, 2 do
+ tc.tv1.should == 2
+ end
+ tc.tv1.should == 1
tc.clear_tv1.should == tc
tc.tv1.should == nil
}
@@ -44,6 +48,10 @@ def ti
ti.iv1.should == nil
ti.iv1 = 1
ti.iv1.should == 1
+ ti.with_attr! :iv1, 2 do
+ ti.iv1.should == 2
+ end
+ ti.iv1.should == 1
ti.clear_iv1.should == ti
ti.iv1.should == nil
rescue Exception => exc

0 comments on commit 91ac2a0

Please sign in to comment.