Module: Tuile::Locale::Formats

Defined in:
lib/tuile/locale.rb,
sig/tuile.rbs

Overview

The strftime lexer, shared by every format validator here — one tokenizer, so DateFormats and TimeFormats cannot drift on what a directive is:

Formats.each_directive("%d.%m.%Y") { |t| p t }   # "%d", ".", "%m", ".", "%Y"

Each validator over it supplies the rest — a reference value to round-trip against, a hint table, its own by-name rejections. See DateFormats and TimeFormats.

Constant Summary collapse

DIRECTIVE =

Any strftime directive, known or not — flags, width, the E/O modifiers and the %::z colons included. Matching the ones a caller cannot translate is the point: they must reach a hint table's miss rather than falling through as literal text, or "%Y-%j" would humanize to the lying hint "yyyy-%j".

Returns:

  • (Regexp)
/%[-_0^#]*\d*[EO]?:{0,2}[A-Za-z%]/
LOCALE_LOOKALIKES =

They look like a locale channel and are not: Ruby's %x is a fixed "09/04/26" under every locale, and it round-trips — so it would pass validation while silently meaning "American". Rejected by name by every validator here.

Returns:

  • (Array<String>)
%w[%x %X %c].freeze

Class Method Summary collapse

Class Method Details

.each_directive(format) ⇒ void

This method returns an undefined value.

Yields each strftime directive in format, and each character between them one at a time — so a caller can tell "%%" (one directive, a literal percent) from a bare "%" that is merely text.

@param format

Parameters:

  • format (String)


111
112
113
114
115
116
117
# File 'lib/tuile/locale.rb', line 111

def each_directive(format)
  scanner = StringScanner.new(format)
  until scanner.eos?
    directive = scanner.scan(DIRECTIVE)
    yield(directive || scanner.getch)
  end
end

.humanize(format, hints) ⇒ String?

Translates a format through hints, or nil when it holds any directive the table does not cover — never a half-translated hint.

Formats.humanize("%d.%m.%Y", DateFormats::HINTS)   # => "dd.mm.yyyy"

@param format

@param hints

@return — frozen.

Parameters:

  • format (String)
  • hints (::Hash[String, String])

Returns:

  • (String, nil)


131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/tuile/locale.rb', line 131

def humanize(format, hints)
  hint = +""
  each_directive(format) do |directive|
    next hint << directive if directive.length == 1

    translated = hints[directive]
    return nil if translated.nil?

    hint << translated
  end
  hint.freeze
end

.lookalike(format) ⇒ String?

@param format

@return — the first locale lookalike in format, or nil.

Parameters:

  • format (String)

Returns:

  • (String, nil)


121
# File 'lib/tuile/locale.rb', line 121

def lookalike(format) = LOCALE_LOOKALIKES.find { format.include?(_1) }