module Plurality

Constants

ORDINALS
TOKENS
VERSION
WORDS

Public Instance Methods

t(*args)
Alias for: translate
translate(*args) click to toggle source
# File lib/plurality.rb, line 15
def translate(*args)
  options = args.last.is_a?(Hash) ? args.pop.dup : {}
  key = args.shift
  nouns = options.delete(:nouns).to_a
  translations = I18n.t!(key, scope: options[:scope])
  numbers = translations.keys
  other = numbers.delete(:other)
  count = nouns.count
  threshold = WORDS.key(numbers.last)

  if other.nil? || count <= threshold
    number = WORDS[count]
    string = translations[number]
  else
    number = :other
    string = translations[:other]
  end

  raise MissingPluralData, "Missing for #{WORDS[count] || count} nouns" if string.nil?

  options[:scope] = generate_scope key, options[:scope]  
  options[:additional] = calculate_additonal(count, string)
  options.merge! ordinalized_nouns(nouns, threshold)

  I18n.t number, options
end
Also aliased as: t

Private Instance Methods

calculate_additonal(count, string) click to toggle source
# File lib/plurality.rb, line 45
def calculate_additonal(count, string)
  tokens = string.scan(TOKENS).flatten.count { |t| ORDINALS.has_value? t }
  count - tokens
end
generate_scope(key, scope) click to toggle source
# File lib/plurality.rb, line 50
def generate_scope(key, scope)
  I18n.normalize_keys(nil, key, scope)
end
ordinalized_nouns(nouns, number) click to toggle source
# File lib/plurality.rb, line 54
def ordinalized_nouns(nouns, number)
  Hash[ORDINALS.values.take(number).map(&:to_sym).zip(nouns.take(number))].delete_if { |k, v| v.nil? }
end