Module: Translateable::ClassMethods
- Defined in:
- lib/translateable.rb
Instance Method Summary collapse
- #database_connection_exists? ⇒ Boolean
- #define_translateable_methods(attr) ⇒ Object
- #define_translateable_strong_params(*attrs) ⇒ Object
- #translateable(*attrs) ⇒ Object
- #translateable_sanity_check(attr) ⇒ Object
Instance Method Details
#database_connection_exists? ⇒ Boolean
36 37 38 39 40 |
# File 'lib/translateable.rb', line 36 def database_connection_exists? ActiveRecord::Base.connection_pool.with_connection(&:active?) rescue StandardError false end |
#define_translateable_methods(attr) ⇒ Object
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
# File 'lib/translateable.rb', line 42 def define_translateable_methods(attr) define_method("#{attr}_fetch_translateable") do value = self[attr] return value.with_indifferent_access if !value.nil? && !value.empty? (new_record? ? { I18n.locale => '' } : {}).with_indifferent_access end define_method(Translateable.translateable_attribute_by_name(attr)) do value = send("#{attr}_fetch_translateable") value.map { |k, v| AttributeValue.new(locale: k, data: v) } end define_method("#{attr}_translateable_attributes=") do |arg| self[attr] = arg.each_with_object({}) do |i, obj| hash = i.second next if hash[:_destroy] obj[hash[:locale]] = hash[: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| value = arg.is_a?(Hash) ? arg : (self[attr] || {}).merge(I18n.locale => arg) self[attr] = value end end |
#define_translateable_strong_params(*attrs) ⇒ Object
30 31 32 33 34 |
# File 'lib/translateable.rb', line 30 def define_translateable_strong_params(*attrs) define_singleton_method('translateable_permitted_attributes') do attrs.each_with_object([]) { |i, obj| obj << { "#{i}_translateable_attributes" => %i(locale data _destroy) } } end end |
#translateable(*attrs) ⇒ Object
15 16 17 18 19 20 21 |
# File 'lib/translateable.rb', line 15 def translateable(*attrs) attrs.each do |attr| translateable_sanity_check(attr) define_translateable_methods(attr) end define_translateable_strong_params(*attrs) end |
#translateable_sanity_check(attr) ⇒ Object
23 24 25 26 27 28 |
# File 'lib/translateable.rb', line 23 def translateable_sanity_check(attr) return if ENV['DISABLE_TRANSLATEABLE_SANITY_CHECK'] return unless database_connection_exists? attr = attr.to_s raise ArgumentError, "no such column '#{attr}' in '#{name}' model" unless column_names.include?(attr) end |