Sha256: e62c5a984c577cb815433c009727d4427e04bba3062c07fd31e38c372e983e9d

Contents?: true

Size: 1.72 KB

Versions: 4

Compression:

Stored size: 1.72 KB

Contents

# encoding: utf-8
module Mongoid #:nodoc:
  module Fields #:nodoc:
    module Internal #:nodoc:

      # Defines the behaviour for localized string fields.
      class Localized
        include Serializable

        # Deserialize the object based on the current locale. Will look in the
        # hash for the current locale.
        #
        # @example Get the deserialized value.
        #   field.deserialize({ "en" => "testing" })
        #
        # @param [ Hash ] object The hash of translations.
        #
        # @return [ String ] The value for the current locale.
        #
        # @since 2.3.0
        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

        # Special case to serialize the object.
        #
        # @example Convert to a selection.
        #   field.selection(object)
        #
        # @param [ Object ] The object to convert.
        #
        # @return [ Object ] The converted object.
        #
        # @since 2.4.0
        def selection(object)
          return object if object.is_a?(::Hash)
          serialize(object)
        end

        # Convert the provided string into a hash for the locale.
        #
        # @example Serialize the value.
        #   field.serialize("testing")
        #
        # @param [ String ] object The string to convert.
        #
        # @return [ Hash ] The locale with string translation.
        #
        # @since 2.3.0
        def serialize(object)
          { ::I18n.locale.to_s => object }
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
mongoid-2.8.1 lib/mongoid/fields/internal/localized.rb
mongoid-2.8.0 lib/mongoid/fields/internal/localized.rb
mongoid-2.7.1 lib/mongoid/fields/internal/localized.rb
mongoid-2.7.0 lib/mongoid/fields/internal/localized.rb