Class: LocalizableModel::Localizer

Inherits:
Object
  • Object
show all
Defined in:
lib/localizable_model/localizer.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model) ⇒ Localizer

Returns a new instance of Localizer.



7
8
9
10
# File 'lib/localizable_model/localizer.rb', line 7

def initialize(model)
  @model         = model
  @configuration = model.class.localizable_configuration
end

Instance Attribute Details

#localeObject

Returns the value of attribute locale.



5
6
7
# File 'lib/localizable_model/localizer.rb', line 5

def locale
  @locale
end

Instance Method Details

#cleanup_localizations!Object



56
57
58
# File 'lib/localizable_model/localizer.rb', line 56

def cleanup_localizations!
  @model.localizations = @model.localizations.select(&:value?)
end

#get(attribute, options = {}) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
# File 'lib/localizable_model/localizer.rb', line 29

def get(attribute, options = {})
  get_options = { locale: }.merge(options)
  find_localizations(
    attribute.to_s,
    get_options[:locale].to_s
  ).try(&:first) ||
    @model.localizations.new(
      locale: get_options[:locale].to_s,
      name: attribute.to_s
    )
end

#locale?Boolean

Returns:

  • (Boolean)


18
19
20
# File 'lib/localizable_model/localizer.rb', line 18

def locale?
  locale ? true : false
end

#localesObject



14
15
16
# File 'lib/localizable_model/localizer.rb', line 14

def locales
  @model.localizations.map(&:locale).uniq
end

#localized_attributesObject



22
23
24
25
26
27
# File 'lib/localizable_model/localizer.rb', line 22

def localized_attributes
  attribute_names.each_with_object({}) do |attr, h|
    h[attr] = {}
    locales.each { |l| h[attr][l] = get_value(attr, l) }
  end
end

#set(attribute, value, options = {}) ⇒ Object



41
42
43
44
45
46
47
48
49
50
# File 'lib/localizable_model/localizer.rb', line 41

def set(attribute, value, options = {})
  set_options = { locale: }.merge(options)
  if value.is_a?(Hash) || value.is_a?(ActionController::Parameters)
    value.each { |loc, val| set(attribute, val, locale: loc) }
  else
    require_locale!(attribute, set_options[:locale])
    get(attribute, locale: set_options[:locale]).value = value
  end
  value
end

#value_for?(attribute) ⇒ Boolean

Returns:

  • (Boolean)


52
53
54
# File 'lib/localizable_model/localizer.rb', line 52

def value_for?(attribute)
  get(attribute).value?
end