Last active
November 5, 2020 06:42
-
-
Save swoker/5108409 to your computer and use it in GitHub Desktop.
Set Redis as I18n Cache in Rails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### Gemfile | |
gem 'redis', '~> 3.0.2' | |
gem 'redis-rails', '~> 3.2.3' | |
### as initializer or in application.rb | |
$redis = Redis.new(:host => 'localhost', :port => 6379) | |
# delete all i18n keys before so they will be reloaded | |
$redis.keys.find_all{|k| k.start_with? "i18n"}.each {|k| $redis.del k} | |
# set cache store to redis | |
YOURAPP::Application.config.cache_store = :redis_store, $redis.id | |
# set I18n cache | |
I18n::Backend::Simple.send(:include, I18n::Backend::Cache) | |
I18n.cache_store = ActiveSupport::Cache.lookup_store(:redis_store) | |
### | |
# now you can test with 2 rails consoles and/or rails server | |
# first console: | |
# displays all commands that are send to redis | |
$redis.monitor {|b| p b} | |
# second console (or load a page with rails server) | |
# you will see the get/set commands in the first console | |
$redis.keys # => [] | |
I18n.t "welcome" # => "Welcome" | |
$redis.keys # => ["i18n/en/..."] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for sharing.
One note if you are chaining backends you need to setup the cache on the chain.
I18n::Backend::Chain.send(:include, I18n::Backend::Cache)