class I18n::Tasks::Data::Router::IsolatingRouter

Route based on source file path

Attributes

base_locale[R]
config_read_patterns[R]

Public Class Methods

new(_adapter, data_config) click to toggle source
# File lib/i18n/tasks/data/router/isolating_router.rb, line 14
def initialize(_adapter, data_config)
  @base_locale = data_config[:base_locale]
  @config_read_patterns = Array.wrap(data_config[:read])
end

Public Instance Methods

alternate_path_for(source_path, locale) click to toggle source
# File lib/i18n/tasks/data/router/isolating_router.rb, line 51
def alternate_path_for(source_path, locale)
  source_path = source_path.dup

  config_read_patterns.each do |pattern|
    regexp = Glob.new(format(pattern, locale: '(*)')).to_regexp
    next unless source_path.match?(regexp)

    source_path.match(regexp) do |match_data|
      (1..match_data.size - 1).reverse_each do |capture_index|
        capture_begin, capture_end = match_data.offset(capture_index)
        source_path.slice!(Range.new(capture_begin, capture_end, true))
        source_path.insert(capture_begin, locale.to_s)
      end
    end

    return source_path
  end

  nil
end
route(locale, forest, &block) click to toggle source

Route keys to destinations @param forest [I18n::Tasks::Data::Tree::Siblings] forest roots are locales. @yieldparam [String] dest_path @yieldparam [I18n::Tasks::Data::Tree::Siblings] tree_slice @return [Hash] mapping of destination => [ [key, value], … ]

# File lib/i18n/tasks/data/router/isolating_router.rb, line 24
def route(locale, forest, &block)
  return to_enum(:route, locale, forest) unless block

  locale = locale.to_s
  out = {}

  forest.keys do |key_namespaced_with_source_path, _node|
    source_path, key = key_namespaced_with_source_path.match(/\A<([^>]*)>\.(.*)/).captures
    target_path = alternate_path_for(source_path, locale)
    next unless source_path && key && target_path

    (out[target_path] ||= Set.new) << "#{locale}.#{key}"
  end

  out.each do |target_path, keys|
    file_namespace_subtree = I18n::Tasks::Data::Tree::Siblings.new(
      nodes: forest.get("#{locale}.<#{alternate_path_for(target_path, base_locale)}>")
    )
    file_namespace_subtree.set_root_key!(locale)

    block.yield(
      target_path,
      file_namespace_subtree.select_keys { |key, _| keys.include?(key) }
    )
  end
end