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.



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

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

#attribute?(attribute) ⇒ Boolean

Returns:

  • (Boolean)


11
12
13
# File 'lib/localizable_model/localizer.rb', line 11

def attribute?(attribute)
  @configuration.attribute?(attribute)
end

#cleanup_localizations!Object



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

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

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



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

def get(attribute, options = {})
  get_options = { locale: 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)


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

def locale?
  locale ? true : false
end

#localesObject



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

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

#localized_attributesObject



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

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



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

def set(attribute, value, options = {})
  set_options = { locale: 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)


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

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