Class: I18n::Tasks::Data::Router::PatternRouter

Inherits:
Object
  • Object
show all
Includes:
KeyPatternMatching
Defined in:
lib/i18n/tasks/data/router/pattern_router.rb

Overview

Route based on key name

Direct Known Subclasses

ConservativeRouter

Constant Summary

Constants included from KeyPatternMatching

KeyPatternMatching::MATCH_NOTHING

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from KeyPatternMatching

#compile_key_pattern, #compile_patterns_re, #key_pattern_re_body

Constructor Details

#initialize(_adapter, data_config) ⇒ PatternRouter

Returns a new instance of PatternRouter.

Examples:

{write:
  # keys matched top to bottom
  [['devise.*', 'config/locales/devise.%{locale}.yml'],
  # default catch-all (same as ['*', 'config/locales/%{locale}.yml'])
  'config/locales/%{locale}.yml']}

Parameters:

  • data_config (Hash)

    a customizable set of options

Options Hash (data_config):

  • write (Array)

    of routes



21
22
23
24
# File 'lib/i18n/tasks/data/router/pattern_router.rb', line 21

def initialize(_adapter, data_config)
  @routes_config = data_config[:write]
  @routes = compile_routes @routes_config
end

Instance Attribute Details

#routesObject (readonly)

Returns the value of attribute routes.



12
13
14
# File 'lib/i18n/tasks/data/router/pattern_router.rb', line 12

def routes
  @routes
end

Instance Method Details

#route(locale, forest) {|dest_path, tree_slice| ... } ⇒ Hash

Route keys to destinations

Parameters:

Yield Parameters:

Returns:

  • (Hash)

    mapping of destination => [ [key, value], … ]



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/i18n/tasks/data/router/pattern_router.rb', line 31

def route(locale, forest, &block)
  return to_enum(:route, locale, forest) unless block

  locale = locale.to_s
  out = {}
  forest.keys do |key, _node|
    pattern, path = routes.detect { |route| route[0] =~ key }
    if pattern
      key_match = $~
      path      = format(path, locale: locale)
      path.gsub!(/\\\d+/) { |m| key_match[m[1..].to_i] }
      (out[path] ||= Set.new) << "#{locale}.#{key}"
    else
      fail CommandError, "Cannot route key #{key}. Routes are #{@routes_config.inspect}"
    end
  end
  out.each do |dest, keys|
    block.yield dest,
                forest.select_keys(root: true) { |key, _| keys.include?(key) }
  end
end