From 1cce1069778f0b500f2176c60225f40b9c2c250d Mon Sep 17 00:00:00 2001 From: Maikel Linke Date: Thu, 23 Jan 2020 15:02:31 +1100 Subject: [PATCH] Use our unit name pluralization in Ruby This code will be used for the shop front and reports. --- lib/open_food_network/option_value_namer.rb | 37 +++++++++++++++++++-- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/lib/open_food_network/option_value_namer.rb b/lib/open_food_network/option_value_namer.rb index 1d387c3f29..64a287308a 100644 --- a/lib/open_food_network/option_value_namer.rb +++ b/lib/open_food_network/option_value_namer.rb @@ -38,8 +38,7 @@ module OpenFoodNetwork else value = @variant.unit_value - unit_name = @variant.product.variant_unit_name - unit_name = unit_name.pluralize if value > 1 + unit_name = pluralize(@variant.product.variant_unit_name, value) end value = value.to_i if value == value.to_i @@ -72,5 +71,39 @@ module OpenFoodNetwork unit end + + def pluralize(unit_name, count) + I18nUnitNames.instance.pluralize(unit_name, count) + end + + # Provides efficient access to unit name inflections. + # The singleton property ensures that the init code is run once only. + # The OptionValueNamer is instantiated in loops. + class I18nUnitNames + include Singleton + + def pluralize(unit_name, count) + return unit_name if count.nil? + + @unit_keys ||= unit_key_lookup + key = @unit_keys[unit_name.downcase] + + return unit_name unless key + + I18n.t(key, scope: "unit_names", count: count, default: unit_name) + end + + private + + def unit_key_lookup + lookup = {} + I18n.t("unit_names").each do |key, translations| + translations.values.each do |translation| + lookup[translation.downcase] = key + end + end + lookup + end + end end end