Class: Spree::TranslationMigrations

Inherits:
Object
  • Object
show all
Defined in:
lib/spree/translation_migrations.rb

Instance Method Summary collapse

Constructor Details

#initialize(resource_class, default_locale) ⇒ TranslationMigrations

Returns a new instance of TranslationMigrations.



3
4
5
6
7
8
9
# File 'lib/spree/translation_migrations.rb', line 3

def initialize(resource_class, default_locale)
  @resource_class = resource_class
  @translations_table = resource_class::Translation.table_name
  @translatable_fields = resource_class.translatable_fields.join(', ')
  @foreign_key = "#{resource_class.table_name.singularize}_id"
  @default_locale = default_locale
end

Instance Method Details

#revert_translation_data_transferObject



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/spree/translation_migrations.rb', line 36

def revert_translation_data_transfer
  translation_table_fields = @resource_class.translatable_fields.map { |f| "#{@translations_table}.#{f}" }.join(', ')
  row_expression = @resource_class.translatable_fields.count == 1 ? 'ROW' : ''

  # Update main table with translations
  @resource_class::Translation.find_each do |translation|
    resource = @resource_class.find(translation[@foreign_key])
    @resource_class.translatable_fields.each do |field|
      resource.update_column(field, translation[field])
    end
  end

  # Clear translations table
  @resource_class::Translation.delete_all
end

#transfer_translation_dataObject



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/spree/translation_migrations.rb', line 11

def transfer_translation_data
  nullify_translatable_fields = @resource_class.translatable_fields.map { |f| "#{f}=null" }.join(', ')

  unless @resource_class::Translation.exists?
    # Copy data from main table to translations table
    @resource_class.find_each do |resource|
      translation_attrs = @resource_class.translatable_fields.each_with_object({}) do |field, attrs|
        attrs[field] = resource[field]
      end

      @resource_class::Translation.create!(
        translation_attrs.merge(
          @foreign_key => resource.id,
          locale: @default_locale,
          created_at: resource.created_at,
          updated_at: resource.updated_at
        )
      )
    end

    # Nullify translatable fields in main table
    @resource_class.update_all(nullify_translatable_fields)
  end
end