Module: Mobility::Backends::Serialized

Extended by:
Mobility::Backend::OrmDelegator
Defined in:
lib/mobility/backends/serialized.rb

Overview

Stores translations as serialized attributes in a single text column. This implies that the translated values are not searchable, and thus this backend is not recommended unless specific constraints prevent use of other solutions.

To use this backend, ensure that the model table has a text column on its table with the same name as the translated attribute.

==Backend Options

===+format+

Format for serialization. Either :yaml (default) or :json.

Backend Configuration collapse

Class Method Summary collapse

Methods included from Mobility::Backend::OrmDelegator

for

Class Method Details

.attr_checker(attributes_extractor) ⇒ Object



64
65
66
67
68
69
70
71
# File 'lib/mobility/backends/serialized.rb', line 64

def attr_checker(attributes_extractor)
  lambda do |cond|
    if keys = attributes_extractor.call(cond)
      raise ArgumentError,
        "You cannot query on mobility attributes translated with the Serialized backend (#{keys.join(", ")})."
    end
  end
end

.configure(options) ⇒ Object

Parameters:

  • options (Hash)

    a customizable set of options

Options Hash (options):

  • format (Symbol) — default: :yaml

    Serialization format

Raises:

  • (ArgumentError)

    if a format other than :yaml or :json is passed in



32
33
34
35
36
# File 'lib/mobility/backends/serialized.rb', line 32

def configure(options)
  options[:format] ||= :yaml
  options[:format] = options[:format].downcase.to_sym
  raise ArgumentError, "Serialized backend only supports yaml or json formats." unless [:yaml, :json].include?(options[:format])
end

.deserializer_for(format) ⇒ Object



55
56
57
58
59
60
61
62
# File 'lib/mobility/backends/serialized.rb', line 55

def deserializer_for(format)
  case format
  when :yaml
    lambda { |v| YAML.load(v) }
  when :json
    lambda { |v| JSON.parse(v, symbolize_names: true) }
  end
end

.serializer_for(format) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/mobility/backends/serialized.rb', line 39

def serializer_for(format)
  lambda do |obj|
    return if obj.nil?
    if obj.is_a? Hash
      obj = obj.inject({}) do |translations, (locale, value)|
        translations[locale] = value.to_s if Util.present?(value)
        translations
      end
    else
      raise ArgumentError, "Attribute is supposed to be a Hash, but was a #{obj.class}. -- #{obj.inspect}"
    end

    obj.send("to_#{format}")
  end
end