Module: Russian

Defined in:
lib/russian.rb,
lib/russian/version.rb,
lib/russian/strptime.rb,
lib/russian/russian_rails.rb,
lib/russian/transliteration.rb,
lib/russian/action_view_ext/helpers/date_helper.rb,
lib/russian/active_model_ext/custom_error_message.rb

Overview

Russian language support for Ruby: I18n helpers and Rails integration.

The module wraps common gem I18n operations, adds its own helpers, and installs Rails-specific patches when Rails is detected.

Don’t forget to check README!

Поддержка русского языка для Ruby: библиотеки I18n и интеграция с Rails.

Модуль оборачивает типичные операции gem’а I18n, добавляет свои, и устанавливает Rails-специфичные патчи, если обнаружен Rails.

Не забудьте прочитать README!

Examples:

require "russian"
Russian.t(:"date.formats.default")
Russian.l(Date.new(1985, 12, 1), format: :long)
Russian.translit("Привет")

Defined Under Namespace

Modules: ActionViewExt, ActiveModelExt, RailsIntegration, Strptime, Transliteration, VERSION

Constant Summary collapse

LOCALE =

Locale used by the gem.

Локаль, которую использует gem.

Returns:

  • (Symbol)

    Russian locale identifier. Идентификатор русской локали.

:ru
LOCALIZE_ABBR_MONTH_NAMES_MATCH =
/(%[-_0^#:]*(\d+)*[EO]?d|%[-_0^#:]*(\d+)*[EO]?e)(.*)(%b)/
LOCALIZE_MONTH_NAMES_MATCH =
/(%[-_0^#:]*(\d+)*[EO]?d|%[-_0^#:]*(\d+)*[EO]?e)(.*)(%B)/
LOCALIZE_STANDALONE_ABBR_DAY_NAMES_MATCH =
/^%a/
LOCALIZE_STANDALONE_DAY_NAMES_MATCH =
/^%A/
STRPTIME_DIRECTIVE_MODIFIERS =
"-_0^#:"

Class Method Summary collapse

Class Method Details

.date_strptime(string, format = "%F") ⇒ Date

Parses a localized Russian date string with Date.strptime.

The method understands Russian month and weekday names, normalizes them to the English names expected by Ruby’s parser, and then delegates to Date.strptime. All non-localized directives are still handled by the native Ruby parser.

Разбирает локализованную русскую строку даты через Date.strptime.

Метод понимает русские названия месяцев и дней недели, нормализует их к английским именам, которые ожидает стандартный parser Ruby, а затем делегирует работу в Date.strptime. Все остальные директивы по-прежнему обрабатываются нативным parser’ом Ruby.

Examples:

Russian.date_strptime("01 апреля 2011", "%d %B %Y")
# => #<Date: 2011-04-01 ...>

Parameters:

  • string (String)

    Localized date string. Локализованная строка даты.

  • format (String) (defaults to: "%F")

    Optional strptime format string. Строка формата strptime.

Returns:

  • (Date)

    Parsed date. Разобранная дата.



236
237
238
# File 'lib/russian.rb', line 236

def date_strptime(string, format = "%F")
  Strptime.date_strptime(string, format)
end

.datetime_strptime(string, format = "%FT%T%z") ⇒ DateTime

Parses a localized Russian date/time string with DateTime.strptime.

The method uses the same Russian textual token normalization as date_strptime, then delegates to DateTime.strptime.

Разбирает локализованную русскую строку даты и времени через DateTime.strptime.

Метод использует ту же нормализацию русских текстовых токенов, что и date_strptime, а затем делегирует работу в DateTime.strptime.

Examples:

Russian.datetime_strptime("01 апреля 2011 23:45:05 +0300", "%d %B %Y %H:%M:%S %z")
# => #<DateTime: 2011-04-01T23:45:05+03:00 ...>

Parameters:

  • string (String)

    Localized date/time string. Локализованная строка даты и времени.

  • format (String) (defaults to: "%FT%T%z")

    Optional strptime format string. Строка формата strptime.

Returns:

  • (DateTime)

    Parsed datetime. Разобранный DateTime.



290
291
292
# File 'lib/russian.rb', line 290

def datetime_strptime(string, format = "%FT%T%z")
  Strptime.datetime_strptime(string, format)
end

.init_i18nvoid

This method returns an undefined value.

Installs Russian locale files into I18n and reloads the I18n backend.

The method is safe to call repeatedly. It prepends this gem’s locale files to I18n.load_path, enables pluralization and transliteration backends, and then calls I18n.reload!.

Подключает файлы русской локали к I18n и перезагружает backend I18n.

Метод безопасно вызывать повторно. Он добавляет locale-файлы gem’а в начало I18n.load_path, включает backend’ы pluralization и transliteration, а затем вызывает I18n.reload!.

Examples:

I18n.load_path.clear
Russian.init_i18n
I18n.t(:"date.month_names", locale: :ru)


88
89
90
91
92
93
94
95
96
# File 'lib/russian.rb', line 88

def init_i18n
  backend = I18n::Backend::Simple

  backend.include(I18n::Backend::Pluralization)
  backend.include(I18n::Backend::Transliterator)

  I18n.load_path = locale_files + (I18n.load_path - locale_files)
  I18n.reload!
end

.localeSymbol

Returns the locale used by the gem.

Возвращает локаль, которую использует gem.

Examples:

Russian.locale
# => :ru

Returns:

  • (Symbol)

    Russian locale identifier. Идентификатор русской локали.



65
66
67
# File 'lib/russian.rb', line 65

def locale
  LOCALE
end

.localize(object, options = nil, **kwargs) ⇒ String Also known as: l

Localizes an object using the Russian locale by default.

Both the legacy positional hash and modern keyword arguments are supported.

Локализует объект, по умолчанию используя русскую локаль.

Поддерживаются и устаревший positional hash, и современные keyword-аргументы.

Examples:

Russian.localize(Date.new(1985, 12, 1), format: :long)
Russian.localize(Date.new(1985, 12, 1), {format: :long})

Parameters:

  • object (Object)

    Localizable object, usually Date, Time, or DateTime. Локализуемый объект, обычно Date, Time или DateTime.

  • options (Hash, nil) (defaults to: nil)

    Legacy positional I18n options hash. Устаревший positional hash с опциями I18n.

  • kwargs (Hash)

    Keyword I18n options. Keyword-опции I18n.

Returns:

  • (String)

    Localized string. Локализованная строка.

Raises:

  • (ArgumentError)

    if options is not a hash. Если options не является hash’ем.



162
163
164
# File 'lib/russian.rb', line 162

def localize(object, options = nil, **kwargs)
  I18n.localize(object, **normalize_i18n_options(options, kwargs, locale: LOCALE))
end

.pluralize(n, *variants) ⇒ Object Also known as: p

Returns the correct Russian plural form for a numeric value.

For integers, three variants are required: one, few, and many. For non-integer numbers, a fourth other variant is also required.

Возвращает правильную русскую форму множественного числа для числового значения.

Для целых чисел нужны три варианта: one, few и many. Для дробных чисел дополнительно нужен четвертый вариант other.

Examples:

Russian.pluralize(1, "вещь", "вещи", "вещей")
# => "вещь"
Russian.pluralize(3.14, "вещь", "вещи", "вещей", "вещи")
# => "вещи"

Parameters:

  • n (Numeric)

    Number used for pluralization. Число для выбора формы.

  • variants (Array<Object>)

    Pluralization variants in the order one, few, many, other. Варианты в порядке one, few, many, other.

Returns:

  • (Object)

    Selected pluralization variant. Выбранный вариант склонения.

Raises:

  • (ArgumentError)

    if n is not numeric or required variants are missing. Если n не число или не переданы нужные варианты.



320
321
322
323
324
325
326
327
# File 'lib/russian.rb', line 320

def pluralize(n, *variants)
  raise ArgumentError, "Must have a Numeric as a first parameter" unless n.is_a?(Numeric)
  raise ArgumentError, "Must have at least 3 variants for pluralization" if variants.size < 3
  raise ArgumentError, "Must have at least 4 variants for pluralization" if variants.size < 4 && n != n.round

  variants_hash = pluralization_variants_to_hash(*variants)
  I18n.backend.send(:pluralize, LOCALE, variants_hash, n)
end

.strftime(object, format = :default, **kwargs) ⇒ String

Localizes an object using a strftime-style format identifier.

‘Russian.strftime(time, :long)` and `Russian.strftime(time, format: :long)` are both supported.

Локализует объект, используя идентификатор формата в стиле strftime.

Поддерживаются форматы ‘Russian.strftime(time, :long)` и `Russian.strftime(time, format: :long)`.

Examples:

Russian.strftime(Time.new(2008, 9, 1, 11, 12, 43, "+03:00"), :long)
Russian.strftime(Time.new(2008, 9, 1, 11, 12, 43, "+03:00"), format: :long)

Parameters:

  • object (Object)

    Localizable object. Локализуемый объект.

  • format (Symbol, Hash) (defaults to: :default)

    Format name or legacy options hash. Имя формата или устаревший hash с опциями.

  • kwargs (Hash)

    Keyword I18n options. Keyword-опции I18n.

Returns:

  • (String)

    Localized string. Локализованная строка.

Raises:

  • (ArgumentError)

    if a legacy options argument is not a hash. Если устаревший аргумент с опциями не является hash’ем.



200
201
202
203
204
205
206
207
208
209
# File 'lib/russian.rb', line 200

def strftime(object, format = :default, **kwargs)
  options =
    if format.is_a?(Hash)
      normalize_i18n_options(format, kwargs)
    else
      normalize_i18n_options({format: format}, kwargs)
    end

  localize(object, **options)
end

.time_strptime(string, format, now = Time.now) ⇒ Time

Parses a localized Russian date/time string with Time.strptime.

The method uses the same Russian textual token normalization as date_strptime, then delegates to Time.strptime.

Разбирает локализованную русскую строку даты и времени через Time.strptime.

Метод использует ту же нормализацию русских текстовых токенов, что и date_strptime, а затем делегирует работу в Time.strptime.

Examples:

Russian.time_strptime("01 апреля 2011 23:45:05 +0300", "%d %B %Y %H:%M:%S %z")
# => 2011-04-01 23:45:05 +0300

Parameters:

  • string (String)

    Localized date/time string. Локализованная строка даты и времени.

  • format (String)

    strptime format string. Строка формата strptime.

  • now (Time) (defaults to: Time.now)

    Optional base time passed to Time.strptime. Базовое значение времени, передаваемое в Time.strptime.

Returns:

  • (Time)

    Parsed time. Разобранное время.



264
265
266
# File 'lib/russian.rb', line 264

def time_strptime(string, format, now = Time.now)
  Strptime.time_strptime(string, format, now)
end

.translate(key, options = nil, **kwargs) ⇒ Object Also known as: t

Translates a key using the Russian locale by default.

Both the legacy positional hash and modern keyword arguments are supported.

Переводит ключ, по умолчанию используя русскую локаль.

Поддерживаются и устаревший positional hash, и современные keyword-аргументы.

Examples:

Russian.translate(:"date.formats.default")
Russian.translate(:"date.formats.default", scope: :foo)
Russian.translate(:"date.formats.default", {scope: :foo})

Parameters:

  • key (String, Symbol)

    Translation key. Ключ перевода.

  • options (Hash, nil) (defaults to: nil)

    Legacy positional I18n options hash. Устаревший positional hash с опциями I18n.

  • kwargs (Hash)

    Keyword I18n options. Keyword-опции I18n.

Returns:

  • (Object)

    Translation result returned by I18n. Результат перевода, возвращаемый I18n.

Raises:

  • (ArgumentError)

    if options is not a hash. Если options не является hash’ем.



124
125
126
# File 'lib/russian.rb', line 124

def translate(key, options = nil, **kwargs)
  I18n.translate(key, **normalize_i18n_options(options, kwargs, locale: LOCALE))
end

.transliterate(str) ⇒ String Also known as: translit

Transliterates a string from Cyrillic to Latin characters.

The method delegates to Russian::Transliteration.transliterate and preserves the historical casing behavior of the gem.

Транслитерирует строку из кириллицы в латиницу.

Метод делегирует работу в Russian::Transliteration.transliterate и сохраняет историческое поведение gem’а по работе с регистром.

Examples:

Russian.transliterate("Юлия")
# => "Yuliya"

Parameters:

  • str (String)

    String to transliterate. Строка для транслитерации.

Returns:

  • (String)

    Transliteration result. Результат транслитерации.



357
358
359
# File 'lib/russian.rb', line 357

def transliterate(str)
  Transliteration.transliterate(str)
end