Skip to content

Commit

Permalink
experimental backend/cache implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
Sven Fuchs committed Jul 15, 2009
1 parent dcefa54 commit e7bf153
Show file tree
Hide file tree
Showing 2 changed files with 89 additions and 0 deletions.
54 changes: 54 additions & 0 deletions lib/i18n/backend/cache.rb
@@ -0,0 +1,54 @@
# This module allows you to easily cache all responses from the backend - thus
# speeding up the I18n aspects of your application quite a bit.
#
# To enable caching you can simply include the Cache module to the Simple
# backend - or whatever other backend you are using:
#
# I18n::Backend::Simple.send(:include, I18n::Backend::Cache)
#
# You will also need to set a cache store implementation that you want to use:
#
# I18n.cache_store = ActiveSupport::Cache.lookup_store(:memory_store)
#
# You can use any cache implementation you want that provides the same API as
# the ActiveSupport::Cache API.
module I18n
class << self
@@cache_store = nil

def cache_store
@@cache_store
end

def cache_store=(store)
@@cache_store = store
end

def perform_caching?
!cache_store.nil?
end
end

module Backend
module Cache
def translate(*args)
I18n.perform_caching? ? fetch(*args) { super } : super
end

protected

def fetch(*args, &block)
result = I18n.cache_store.fetch(cache_key(*args), &block)
raise result if result.is_a?(Exception)
result
rescue MissingTranslationData => exception
I18n.cache_store.write(cache_key(*args), exception)
raise exception
end

def cache_key(*args)
args.hash
end
end
end
end
35 changes: 35 additions & 0 deletions test/backend/cache/cache_test.rb
@@ -0,0 +1,35 @@
require File.expand_path(File.dirname(__FILE__) + '/../../test_helper')
require 'i18n/backend/cache'
require 'activesupport'

class I18nCacheBackendTest < Test::Unit::TestCase
def setup
super
class << I18n.backend
include I18n::Backend::Cache
end
I18n.cache_store = ActiveSupport::Cache.lookup_store(:memory_store)
end

def teardown
I18n.cache_store = nil
end

define_method :"test translate hits the backend and caches the response" do
I18n.backend.expects(:lookup).returns('Foo')
assert_equal 'Foo', I18n.t(:foo)

I18n.backend.expects(:lookup).never
assert_equal 'Foo', I18n.t(:foo)

I18n.backend.expects(:lookup).returns('Bar')
assert_equal 'Bar', I18n.t(:bar)
end

define_method :"test still raises MissingTranslationData but also caches it" do
I18n.backend.expects(:lookup).returns(nil)
assert_raises(I18n::MissingTranslationData) { I18n.t(:missing, :raise => true) }
I18n.backend.expects(:lookup).never
assert_raises(I18n::MissingTranslationData) { I18n.t(:missing, :raise => true) }
end
end

0 comments on commit e7bf153

Please sign in to comment.