Sha256: 36d526fd6770186c31924e663848eee0295a92ff0ae98bbd58da762939868eb2

Contents?: true

Size: 1.94 KB

Versions: 2

Compression:

Stored size: 1.94 KB

Contents

module PufferPages
  module Backends
    module Mixins
      module Translatable
        extend ActiveSupport::Concern

        module ClassMethods
          def translatable *fields
            if PufferPages.localize
              translates *fields, fallbacks_for_empty_translations: true
              translation_class.send(:include, ActiveUUID::UUID)

              def self.globalize_migrator
                @globalize_migrator ||= PufferPages::Globalize::Migrator.new(self)
              end

              fields.each do |field|
                define_method "#{field}_translations" do
                  result = translations.each_with_object(HashWithIndifferentAccess.new) do |translation, result|
                    result[translation.locale] = translation.send(field)
                  end
                  globalize.stash.keys.each_with_object(result) do |locale, result|
                    result[locale] = globalize.stash.read(locale, field) if globalize.stash.contains?(locale, field)
                  end
                end

                define_method "#{field}_translations=" do |value|
                  value.each do |(locale, value)|
                    write_attribute(field, value, locale: locale)
                  end
                end
              end

              define_method :serializable_hash_with_translations do |options = nil|
                options ||= {}
                except = Array.wrap(options[:except])
                options[:except] = except +
                  self.class.translated_attribute_names.map(&:to_s)
                methods = Array.wrap(options[:methods])
                options[:methods] = methods +
                  self.class.translated_attribute_names.map { |name| "#{name}_translations" }
                serializable_hash_without_translations options
              end

              alias_method_chain :serializable_hash, :translations
            end
          end
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
puffer_pages-0.5.1 lib/puffer_pages/backends/models/mixins/translatable.rb
puffer_pages-0.5.0 lib/puffer_pages/backends/models/mixins/translatable.rb