Class: Vldt::I18n

Inherits:
Object
  • Object
show all
Defined in:
lib/vldt/i18n.rb

Overview

i18n integration for vldt

Constant Summary collapse

I18N_OPTIONS =

Default options for the t call

{ default: false, exception_handler: -> (*args) { false } }

Class Method Summary collapse

Class Method Details

.t(result, namespace: nil) ⇒ Object

Add translated error messages to the errors.

Examples:

Vldt::I18n.t({ [:user, :name] => [{ type: :string_length_greater_than, params: { min: 5 } }] })
# This will try to look up from top to bottom
# - user.name.string_length_greater_than
# - name.string_length_greater_than
# - string_length_greater_than
# - vldt.errors.string_length_greater_than
# And pass the { min: 5 } to all of them for interpolation

Usage with a namespace

Vldt::I18n.t({ [] => [{ type: :between, { min: 2, max: 5 } }]}, namespace: "my.app")
# This will try to look up
# - my.app.between
# - vldt.errors.between

Parameters:

  • result

    The result of a validation

Returns:

  • The result with added :message keys



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/vldt/i18n.rb', line 28

def self.t (result, namespace: nil)
  with_messages = result.map do |selector, errors|
    new_errors = errors.map do |error|
      e = error.dup
      options = I18N_OPTIONS.merge(e[:params])

      scopes(selector, namespace).each do |scope|
        options[:scope] = scope

        message = ::I18n.t(e[:type], options)

        if message
          e[:message] = message

          break
        end
      end

      e
    end

    [selector, new_errors]
  end

  ::Hash[with_messages]
end