Module: HaveAPI::I18n

Defined in:
lib/haveapi/i18n.rb

Class Method Summary collapse

Class Method Details

.accept_language(header, available_locales) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/haveapi/i18n.rb', line 60

def accept_language(header, available_locales)
  header.to_s.split(',').each_with_index.filter_map do |raw, index|
    tag, *params = raw.strip.split(';')
    next if tag.nil? || tag.empty?

    q = params.map(&:strip).grep(/\Aq=/).first
    weight = q ? q.split('=', 2).last.to_f : 1.0
    next if weight <= 0.0

    [tag, weight, index]
  end.sort_by { |(_, weight, index)| [-weight, index] }.each do |tag, _, _|
    locale = normalize_locale(tag, available_locales)
    return locale if locale
  end

  nil
rescue StandardError
  nil
end

.available_localesObject



52
53
54
55
56
57
58
# File 'lib/haveapi/i18n.rb', line 52

def available_locales
  locale_dir = File.expand_path('locales', __dir__)

  Dir[File.join(locale_dir, '*.yml')].map do |path|
    File.basename(path, '.yml').to_sym
  end.sort
end

.normalize_locale(locale, available_locales) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/haveapi/i18n.rb', line 80

def normalize_locale(locale, available_locales)
  return if locale.nil?

  tag = locale.to_s.strip.tr('_', '-')
  return if tag.empty? || tag == '*'

  available = Array(available_locales).map(&:to_s)
  candidates = [tag, tag.split('-').first].compact.map(&:downcase).uniq

  candidates.each do |candidate|
    match = available.detect { |v| v.downcase == candidate }
    return match.to_sym if match
  end

  nil
end

.setupObject



47
48
49
50
# File 'lib/haveapi/i18n.rb', line 47

def setup
  locale_dir = File.expand_path('locales', __dir__)
  ::I18n.load_path |= Dir[File.join(locale_dir, '*.yml')]
end