diff --git a/lib/rhino/rhino_ext.rb b/lib/rhino/rhino_ext.rb index ed5ce04..51ca2f3 100644 --- a/lib/rhino/rhino_ext.rb +++ b/lib/rhino/rhino_ext.rb @@ -173,3 +173,43 @@ class Java::OrgMozillaJavascript::BaseFunction end end + +class Java::OrgMozillaJavascript::Context + + def reset_cache! + @cache = java.util.WeakHashMap.new + end + + def enable_cache! + @cache = nil unless @cache + end + + def disable_cache! + @cache = false + end + + # Support for caching JS data per context. + # e.g. to get === comparison's working ... + # + # NOTE: the cache only works correctly for keys following Java identity ! + # (implementing #equals & #hashCode e.g. RubyStrings will work ...) + # + def cache(key) + return yield if @cache == false + reset_cache! unless @cache + fetch(key) || store(key, yield) + end + + private + + def fetch(key) + ref = @cache.get(key) + ref ? ref.get : nil + end + + def store(key, value) + @cache.put(key, java.lang.ref.WeakReference.new(value)) + value + end + +end diff --git a/lib/rhino/ruby.rb b/lib/rhino/ruby.rb index 560d393..cb78f22 100644 --- a/lib/rhino/ruby.rb +++ b/lib/rhino/ruby.rb @@ -207,28 +207,12 @@ module Rhino end end - - def self.cache(key) - return yield unless @@cache - fetch(key) || store(key, yield) + + def self.cache(key, &block) + context = JS::Context.getCurrentContext + context ? context.cache(key, &block) : yield end - private - - # NOTE: just to get === comparison's working ... - # if == is enough might be disabled by setting to nil - @@cache = java.util.WeakHashMap.new - - def self.fetch(key) - ref = @@cache.get(key) - ref ? ref.get : nil - end - - def self.store(key, value) - @@cache.put(key, java.lang.ref.WeakReference.new(value)) - value - end - end RubyObject = Ruby::Object