glebm / i18n-tasks

Manage translation and localization with static analysis, for Ruby i18n
http://glebm.github.io/i18n-tasks
MIT License
2.08k stars 264 forks source link

support for locale.rb #521

Open braindeaf opened 1 year ago

braindeaf commented 1 year ago

Hi, I've just realised the project I'm working on uses i18n-tasks and for the most part things are working fine. I have recently added a few things into an en.rb file. It's not that exciting.

{
  en: {
    date: {
      formats: {
        default: "%d/%m/%Y",
        long: proc { |t, _| "#{t.day.ordinalize} %B %Y" },
        short: proc { |t, _| "#{t.day.ordinalize} %B" }
      }
    },
    core: {
      organisations: {
        edit: {
          title: proc { |_, opts| (opts[:namespace] == :demo) ? "Edit Demo Organisation" : "Edit Organisations" }
        },
        index: {
          title: proc { |_, opts| (opts[:namespace] == :demo) ? "Demo Organisations" : "Organisations" }
        }
      }
    }
  }
}

But it does mean that we can do things like t(".title", namespace: :demo) without much fuss. However, i18n-tasks doesn't support this out of the box for obvious reasons there are missing translations. We could add an additional adapter for this. But while you can read in the translations. when normalising locales it inserts the keys into the en.yml and with a marhalled Proc object which isn't quite what we're after.

# frozen_string_literal: true
module I18n::Tasks
  module Data
    module Adapter
      module RubyAdapter
        class << self
          # @return [Hash] locale tree
          def parse(str, _)
            eval(str)
          end
        end
      end
    end
    class FileSystem < FileSystemBase
      register_adapter :ruby, '*.rb', Adapter::RubyAdapter
    end
  end
end

Is there a way to get this to work, I'd be happy to do a PR given a little guidance.

glebm commented 1 year ago

Adapters are responsible for (de)serialization but the keys themselves are routed to files by a Router

There are a couple of built-in routers: https://github.com/glebm/i18n-tasks/tree/main/lib/i18n/tasks/data/router

conservative_router tries to keep the keys in the files where they were found.\ pattern_router routes the keys to files based on the a list of patterns.

You may want to write a custom Router that deals with the keys found in .rb files in some special way, and falls back to your preferred router for other keys.

The router can be configured in i18n-tasks.yml (https://github.com/glebm/i18n-tasks/tree/a0300907c9b34f2010ba89a8e06d958d8cbd6060#multiple-locale-files).