Module: Translateable::ClassMethods

Defined in:
lib/translateable.rb

Instance Method Summary collapse

Instance Method Details

#database_connection_exists?Boolean



45
46
47
48
49
# File 'lib/translateable.rb', line 45

def database_connection_exists?
  connection_pool.with_connection(&:active?)
rescue StandardError
  false
end

#define_translateable_methods(attr) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/translateable.rb', line 51

def define_translateable_methods(attr)
  define_method("#{attr}_fetch_translateable") do
    (self[attr] || {}).with_indifferent_access
  end

  define_method(Translateable.translateable_attribute_by_name(attr)) do
    value = send("#{attr}_fetch_translateable")
    value = { I18n.locale.to_s => '' } if value.empty? && new_record?
    value.map { |k, v| AttributeValue.new(locale: k, data: v) }
  end

  define_method("#{attr}_translateable_attributes=") do |arg|
    entries = arg.respond_to?(:values) ? arg.values : arg
    self[attr] = entries.each_with_object({}) do |entry, obj|
      entry = entry.with_indifferent_access if entry.is_a?(Hash)
      next if ActiveModel::Type::Boolean.new.cast(entry[:_destroy])
      obj[entry[:locale].to_s] = entry[:data]
    end
  end

  define_method(attr) do |**args|
    value = send("#{attr}_fetch_translateable")
    value[I18n.locale] || (value[I18n.default_locale] unless args[:strict]) || (value.values.first unless args[:strict])
  end

  define_method("#{attr}=") do |arg|
    self[attr] = arg.respond_to?(:to_hash) ? arg.to_hash : (self[attr] || {}).merge(I18n.locale.to_s => arg)
  end
end

#translateable(*attrs, sanity_checks: true) ⇒ Object



21
22
23
24
25
26
27
# File 'lib/translateable.rb', line 21

def translateable(*attrs, sanity_checks: true)
  attrs.each do |attr|
    translateable_sanity_check(attr) if sanity_checks
    define_translateable_methods(attr)
  end
  @translateable_attributes = (@translateable_attributes || []) | attrs
end

#translateable_attributesObject



29
30
31
32
# File 'lib/translateable.rb', line 29

def translateable_attributes
  inherited = superclass.respond_to?(:translateable_attributes) ? superclass.translateable_attributes : []
  inherited | (@translateable_attributes || [])
end

#translateable_permitted_attributesObject



34
35
36
# File 'lib/translateable.rb', line 34

def translateable_permitted_attributes
  translateable_attributes.map { |attr| { "#{attr}_translateable_attributes" => i(locale data _destroy) } }
end

#translateable_sanity_check(attr) ⇒ Object

Raises:

  • (ArgumentError)


38
39
40
41
42
43
# File 'lib/translateable.rb', line 38

def translateable_sanity_check(attr)
  return if ENV['DISABLE_TRANSLATEABLE_SANITY_CHECK']
  return unless database_connection_exists? && table_exists?
  attr = attr.to_s
  raise ArgumentError, "no such column '#{attr}' in '#{name}' model" unless column_names.include?(attr)
end