ruby on rails - How to get all translations from all I18n backends -
i'm creating rake task collect translations existing in rails application , output them file in format (probably yaml of csv).
is there way translations using built-in (or in gem) methods?
currently, best think of iterating on i18n.backend.backends check class , based on perform different actions , in end merge single hash.
something like
all_translations = {} i18n.backend.backends.each |backend| if backend.class == simple translations = backend.send(:translations) # etc elsif backend.class == keyvalue # else else # ... end end
not backends conform same interface (which in opinion pretty horrible), can accomplish need through either monkey-patching or creating own backend based off of 1 of built-in i18n backends.
for example, wanted have redis backend falls default rails i18n backend, , needed work i18n-js gem. since keyvalue backend allows translations entire subtree, possible simulate "translations" method long store under top level key. it's simple doing: backend.translate(:en, 'top-level-key')"
# config/initializers/custom_i18n.js module customi18n def self.backend backend::chain.new end module backend class chain < i18n::backend::chain def initialize super(redisstore.new, i18n::backend::simple.new) end def initialized? backends.all? |backend| !backend.respond_to?(:initialized?) || backend.initialized? end end protected def translations backends.each_with_object({}) |backend, hash| backend.instance_eval if respond_to?(:translations, true) hash.deep_merge! translations else available_locales.each |locale| translations = translate(locale, redisstore::scope, :scope => nil) rescue argumenterror hash.deep_merge!({ locale => translations }) if translations end end end end end end class redisstore < i18n::backend::keyvalue scope = 'redis' def initialize(*args) super(redis.new) end def translate(*args) args << {} unless args.last.is_a?(hash) args.last[:scope] = scope unless args.last.has_key?(:scope) super end def store_translations(locale, data, options = {}) super(locale, { scope => data }, options) end end end end i18n.backend = customi18n.backend so, approach, can like:
redis_backend = i18n.backend.backends.find { |backend| backend.is_a?(customi18n::backend::redisstore) } redis_backend.store_translations(:en, {:foo => { :bar => { :baz => 'qux' } } }) and automatically gets stored under top level key of "redis", can access variety of different ways:
> i18n.backend.send(:translations)[:en][:foo] => {:bar=>{:baz=>"qux"}} > i18n.t('foo') i18n keys: [:en, :foo] => {:bar=>{:baz=>"qux"}} but if @ redis, can see it's stored under top level key:
> redis.new.get('en.redis') => "{\"foo\":{\"bar\":{\"baz\":\"qux\"}}}"
Comments
Post a Comment