Class: Foxtail::Sequence

Inherits:
Object
  • Object
show all
Defined in:
lib/foxtail/sequence.rb

Overview

Manages ordered sequences of Bundles for language fallback.

Examples:

Basic usage

sequence = Foxtail::Sequence.new(bundle_en_us, bundle_en, bundle_default)
sequence.format("hello", name: "World")

Finding the bundle that contains a message

bundle = sequence.find("hello")
puts "Using locale: #{bundle.locale}" if bundle

See Also:

Instance Method Summary collapse

Constructor Details

#initialize(*bundles) ⇒ Sequence

Creates a new Sequence with the given bundles.

Parameters:

  • bundles (Array<Bundle>)

    Bundles in priority order (first = highest priority)



19
20
21
# File 'lib/foxtail/sequence.rb', line 19

def initialize(*bundles)
  @bundles = bundles.flatten.freeze
end

Instance Method Details

#find(*ids) ⇒ Bundle, ...

Finds the first bundle that contains a message with the given ID(s).

Parameters:

  • ids (Array<String>)

    One or more message IDs to find

Returns:

  • (Bundle, nil)

    The first bundle containing the message (single ID)

  • (Array<Bundle, nil>)

    Array of bundles for each ID (multiple IDs)



28
29
30
31
32
33
34
# File 'lib/foxtail/sequence.rb', line 28

def find(*ids)
  if ids.size == 1
    find_bundle(ids.first)
  else
    ids.map {|id| find_bundle(id) }
  end
end

#format(id, errors = nil) ⇒ String

Formats a message using the first bundle that contains it. Keyword arguments are passed through to the bundle’s format method.

Parameters:

  • id (String)

    The message ID

  • errors (Array, nil) (defaults to: nil)

    If provided, errors are collected into this array instead of being ignored.

Returns:

  • (String)

    The formatted message, or the ID if not found



42
43
44
45
# File 'lib/foxtail/sequence.rb', line 42

def format(id, errors=nil, **)
  bundle = find_bundle(id)
  bundle ? bundle.format(id, errors, **) : id.to_s
end