require "thread_local_accessor/version" # An idea from http://coderrr.wordpress.com/2008/04/10/lets-stop-polluting-the-threadcurrent-hash/ class Class def thread_local_accessor name, options = {} m = Module.new m.module_eval %{ def #{name} k = ((Class === self ? self : self.class).object_id.to_s + '_#{name}').to_sym if Thread.current.key?(k) Thread.current[k] else #{options[:default].inspect} end end def #{name}=(val) k = ((Class === self ? self : self.class).object_id.to_s + '_#{name}').to_sym Thread.current[k] = val end } class_eval do include m extend m end end end