Add pluralization in ruby on rails Using Predefined Library for Arabic

Total Blog Views: 48

Blog Status: publish

Created By: swazahmad Created at: 08-05-2021

Tags: ruby on rails pluralization

A Dynamic way to Use Pluralization in ruby on rails for Arabic or English Localization

In pluralization The English pluralized english translations must have 2 keys: one  and other , one for signular, e.g. one: person and other for plural: other: people

For Arabic arabic plural forms are way more complex, so we have to define following keys: zero one  two few many other

For Example Like Below

We need to defined some rule in Arabic Plural so We defined Like Below In special_rule.rb module 

module SpecialRules
  module Arabic
    PLURALIZE = ->(n) do
      case n
      when 0
        :zero
      when 1
        :one
      when 2
        :two
      else
        if (n % 100).in?(10..20)
          :few
        elsif (n % 100).in?(21..99)
          :many
        else
          :other
        end
      end
    end
  end
end

{
  ar: {
    i18n: {
      plural: {
        keys: [:zero, :one, :two, :few, :many, :other],
        rule: SpecialRules::Arabic::PLURALIZE
      },
      transliterate: {
        rule: ->(input) { input.to_s.tr("0123456789.", "٠١٢٣٤٥٦٧٨٩٫") }
      }
    }
  },
  en: {
    i18n: {
      transliterate: {
        rule: ->(input) { input.to_s.tr("٠١٢٣٤٥٦٧٨٩٫", "0123456789.") }
      }
    }
  }
}

Then need to update the ar.yml file

computable:
    item:
      zero: "٠ عنصر"
      one: "١ عنصر"
      two: "عنصرين"
      few: "%{localized_count} عناصر"
      many: "%{localized_count} عنصر"
      other: "%{localized_count} عناصر"

For English We just need to defined en.yml 

computable:
    item:
      one: 1 item
      other: "%{localized_count} items"

Now You can acces those Pluralization in both the langauges

I18n.translate('computable.one', count: 1, localized_count: I18n.transliterate(1.to_s, locale: :ar), locale: :ar) 

Thank You so much for reading Please add your comments 


swazahmad

Swaz is Practice Lead of ROR Developer. he's a Blogger, Mentor, and Rubyst. He has expertise in Javascript also . he's highly skilled in designing, developing and testing web applications. He enjoys being challenged and interesting with projects that need him to



Comments



  • swazahmad | almost 4 years ago
    Awesome Information Thanks For Sharing
Buy traffic for your website

About Shadbox

we have the “Get things executed” lifestyle at our place of work. There are not any excuses, no if’s or however’s in our dictionary. committed to navigating the ship of creativity to create cell answers, we resolve the real-lifestyles troubles of our clients and their clients. Our passion for work has won us many awards, year after 12 months.

Services

Downloads