Class: Mongoid::Fields::Internal::Localized

Inherits:
Object
  • Object
show all
Includes:
Serializable
Defined in:
lib/mongoid/fields/internal/localized.rb

Overview

Defines the behaviour for localized string fields.

Instance Attribute Summary

Attributes included from Serializable

#default_val, #label, #localize, #name, #options

Instance Method Summary collapse

Methods included from Serializable

#constraint, #eval_default, #foreign_key?, #localized?, #metadata, #object_id_field?, #resizable?, #type, #versioned?

Instance Method Details

#deserialize(object) ⇒ String

Deserialize the object based on the current locale. Will look in the hash for the current locale.

Examples:

Get the deserialized value.

field.deserialize({ "en" => "testing" })

Parameters:

  • object (Hash)

    The hash of translations.

Returns:

  • (String)

    The value for the current locale.

Since:

  • 2.3.0



21
22
23
24
25
26
27
28
29
# File 'lib/mongoid/fields/internal/localized.rb', line 21

def deserialize(object)
  return nil if object.nil?
  locale = ::I18n.locale
  if ::I18n.respond_to?(:fallbacks)
    object[::I18n.fallbacks[locale].map(&:to_s).find{ |loc| object[loc] }]
  else
    object[locale.to_s]
  end
end

#selection(object) ⇒ Object

Special case to serialize the object.

Examples:

Convert to a selection.

field.selection(object)

Parameters:

  • The (Object)

    object to convert.

Returns:

  • (Object)

    The converted object.

Since:

  • 2.4.0



41
42
43
44
# File 'lib/mongoid/fields/internal/localized.rb', line 41

def selection(object)
  return object if object.is_a?(::Hash)
  serialize(object)
end

#serialize(object) ⇒ Hash

Convert the provided string into a hash for the locale.

Examples:

Serialize the value.

field.serialize("testing")

Parameters:

  • object (String)

    The string to convert.

Returns:

  • (Hash)

    The locale with string translation.

Since:

  • 2.3.0



56
57
58
# File 'lib/mongoid/fields/internal/localized.rb', line 56

def serialize(object)
  { ::I18n.locale.to_s => object }
end