From 1fab2002e3385c40ef48008b649d78ce5e16a868 Mon Sep 17 00:00:00 2001 From: Nikita Afanasenko Date: Wed, 14 Nov 2012 09:58:33 +0400 Subject: Make XmlMini.with_backend usable with threads `XmlMini.with_backend` now may be safely used with threads: Thread.new do XmlMini.with_backend("REXML") { rexml_power } end Thread.new do XmlMini.with_backend("LibXML") { libxml_power } end Each thread will use it's own backend. --- activesupport/lib/active_support/xml_mini.rb | 38 +++++++++++++++++++++------- 1 file changed, 29 insertions(+), 9 deletions(-) (limited to 'activesupport/lib') diff --git a/activesupport/lib/active_support/xml_mini.rb b/activesupport/lib/active_support/xml_mini.rb index 88f9acb588..d082a0a499 100644 --- a/activesupport/lib/active_support/xml_mini.rb +++ b/activesupport/lib/active_support/xml_mini.rb @@ -76,23 +76,24 @@ module ActiveSupport ) end - attr_reader :backend delegate :parse, :to => :backend + def backend + current_thread_backend || @backend + end + def backend=(name) - if name.is_a?(Module) - @backend = name - else - require "active_support/xml_mini/#{name.downcase}" - @backend = ActiveSupport.const_get("XmlMini_#{name}") - end + backend = name && cast_backend_name_to_module(name) + self.current_thread_backend = backend if current_thread_backend + @backend = backend end def with_backend(name) - old_backend, self.backend = backend, name + old_backend = current_thread_backend + self.current_thread_backend = name && cast_backend_name_to_module(name) yield ensure - self.backend = old_backend + self.current_thread_backend = old_backend end def to_tag(key, value, options) @@ -163,6 +164,25 @@ module ActiveSupport f.content_type = entity['content_type'] f end + + private + + def current_thread_backend + Thread.current[:xml_mini_backend] + end + + def current_thread_backend=(name) + Thread.current[:xml_mini_backend] = name && cast_backend_name_to_module(name) + end + + def cast_backend_name_to_module(name) + if name.is_a?(Module) + name + else + require "active_support/xml_mini/#{name.downcase}" + ActiveSupport.const_get("XmlMini_#{name}") + end + end end XmlMini.backend = 'REXML' -- cgit v1.2.3