Module: TranslateableAttributes::Methods

Defined in:
lib/translateable_attributes/methods.rb

Instance Method Summary collapse

Instance Method Details

#translate_attributes(options = {}) ⇒ Object

rubocop:disable Metrics/AbcSize



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/translateable_attributes/methods.rb', line 4

def translate_attributes(options = {})
  options.each do |attribute, namespace|
    plural_attribute = attribute.to_s.pluralize

    define_method "translated_#{attribute}" do
      value = send(attribute)
      value.present? ? I18n.t("#{namespace}.#{value}", default: value) : value
    end

    define_singleton_method "#{plural_attribute}_for_select" do
      options = I18n.t(namespace, default: nil) || []

      options.each_with_object([]) do |(value, translation), collection|
        collection << [translation, value]
      end
    end

    define_singleton_method "translated_#{attribute}" do |value, translation_options = {}|
      I18n.t([namespace, value].join('.'), **translation_options)
    end

    define_singleton_method "possible_#{plural_attribute}" do
      I18n.t(namespace).keys
    end
  end
end