Class: Mobility::Backend::Table::TranslationsCache

Inherits:
Hash
  • Object
show all
Defined in:
lib/mobility/backend/table.rb

Overview

Simple hash cache to memoize translations as a hash so they can be fetched quickly.

Instance Method Summary collapse

Constructor Details

#initialize {|locale| ... } ⇒ TranslationsCache

Returns a new instance of TranslationsCache.

Yields:

  • (locale)

    Yields locale to block in case attribute is not yet cached, expects a new translation for that locale.

Raises:

  • (ArgumentError)

    if block is not given



69
70
71
72
# File 'lib/mobility/backend/table.rb', line 69

def initialize
  raise ArgumentError, "missing block" unless block_given?
  super() { |hash, locale| hash[locale] = yield(locale) }
end

Instance Method Details

#for(attribute) ⇒ Class

Return wrapper class which reads and writes to only one attribute of this cache.

Parameters:

Returns:

  • (Class)

    Hash-like wrapper object to be used as attribute cache



77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/mobility/backend/table.rb', line 77

def for(attribute)
  cache = self

  Class.new do
    define_singleton_method :[] do |locale|
      cache[locale].send(attribute)
    end

    define_singleton_method :[]= do |locale, value|
      cache[locale].send("#{attribute}=", value)
    end
  end
end