Class: Mobility::Backends::ActiveRecord::KeyValue

Inherits:
Object
  • Object
show all
Includes:
Mobility::Backends::ActiveRecord, KeyValue
Defined in:
lib/mobility/backends/active_record/key_value.rb

Overview

Implements the KeyValue backend for ActiveRecord models.

Examples:

class Post < ActiveRecord::Base
  translates :title, backend: :key_value, association_name: :translations, type: :string
end

post = Post.create(title: "foo")
post.translations
#=> #<ActiveRecord::Associations::CollectionProxy ... >
post.translations.first.value
#=> "foo"
post.translations.first.class
#=> Mobility::ActiveRercord::StringTranslation

Defined Under Namespace

Classes: QueryMethods

Instance Attribute Summary

Attributes included from KeyValue

#association_name

Backend Configuration collapse

Instance Method Summary collapse

Methods included from KeyValue

#each_locale, #initialize, #read, #write

Methods included from Mobility::Backend::OrmDelegator

#for

Methods included from Mobility::Backends::ActiveRecord

included, #setup_query_methods

Class Method Details

.configure(options) ⇒ Object

Parameters:

  • options (Hash)

    a customizable set of options

Options Hash (options):

  • type (Symbol) — default: :text

    Column type to use

  • association_name (Symbol) — default: :text_translations

    Name of association method

  • class_name (String, Class) — default: {Mobility::ActiveRecord::TextTranslation}

    Translation class

Raises:

  • (ArgumentError)

    if type is not either :text or :string



38
39
40
41
42
43
44
45
# File 'lib/mobility/backends/active_record/key_value.rb', line 38

def self.configure(options)
  super
  type = options[:type]
  options[:class_name] ||= Mobility::ActiveRecord.const_get("#{type.capitalize}Translation".freeze)
  options[:class_name] = options[:class_name].constantize if options[:class_name].is_a?(String)
  options[:association_name] ||= :"#{options[:type]}_translations"
  i[type association_name].each { |key| options[key] = options[key].to_sym }
end

Instance Method Details

#translation_for(locale, _options = {}) ⇒ Mobility::ActiveRecord::TextTranslation, Mobility::ActiveRecord::StringTranslation

Returns translation for a given locale, or builds one if none is present.



89
90
91
92
93
# File 'lib/mobility/backends/active_record/key_value.rb', line 89

def translation_for(locale, _options = {})
  translation = translations.find { |t| t.key == attribute && t.locale == locale.to_s }
  translation ||= translations.build(locale: locale, key: attribute)
  translation
end