Class: I18nAdmin::Export::XLS

Inherits:
Base
  • Object
show all
Defined in:
lib/i18n_admin/export/xls.rb

Constant Summary collapse

PAGE_LENGTH =
32_000.0

Instance Attribute Summary collapse

Attributes inherited from Base

#locale

Instance Method Summary collapse

Methods inherited from Base

register

Instance Attribute Details

#export_fileObject

Returns the value of attribute export_file.



9
10
11
# File 'lib/i18n_admin/export/xls.rb', line 9

def export_file
  @export_file
end

#sheetObject (readonly)

Returns the value of attribute sheet.



8
9
10
# File 'lib/i18n_admin/export/xls.rb', line 8

def sheet
  @sheet
end

#spreadsheetObject (readonly)

Returns the value of attribute spreadsheet.



8
9
10
# File 'lib/i18n_admin/export/xls.rb', line 8

def spreadsheet
  @spreadsheet
end

Instance Method Details

#file_pathObject



65
66
67
68
69
70
71
# File 'lib/i18n_admin/export/xls.rb', line 65

def file_path
  @file_path ||= [
    '',
    'tmp',
    I18n.t('i18n_admin.exports.file.name', time: Time.now.strftime('%Y_%m_%d-%H_%M'), lang: locale, ext: 'xls')
  ].join('/')
end

#monitoring_data(_, state) ⇒ Object



73
74
75
# File 'lib/i18n_admin/export/xls.rb', line 73

def monitoring_data(_, state)
  { url: export_file.file.url } if state == 'complete'
end

#perform(locale) ⇒ Object



11
12
13
14
15
16
17
18
19
20
# File 'lib/i18n_admin/export/xls.rb', line 11

def perform(locale)
  @locale = locale
  @spreadsheet = Spreadsheet::Workbook.new
  @sheet = spreadsheet.create_worksheet

  add_headers!

  run
  save
end

#runObject



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/i18n_admin/export/xls.rb', line 22

def run
  default_format = Spreadsheet::Format.new(text_wrap: true)

  index = 0

  translations.each do |key, value|
    value = value.to_s
    original_translation = original_translations[key].to_s
    max_length = [value.length, original_translation.length].max
    pages = (max_length / PAGE_LENGTH).ceil

    pages.times do |page|
      index += 1

      translation_key = if pages > 1
        "#{ key } (#{ page + 1 } / #{ pages })"
      else
        key
      end

      start_offset = page * PAGE_LENGTH

      row = sheet.row(index)
      row.default_format = default_format
      row.push(translation_key)
      row.push(original_translation[start_offset, PAGE_LENGTH])
      row.push(value[start_offset, PAGE_LENGTH])
    end
  end
end

#saveObject



53
54
55
56
57
58
59
60
61
62
63
# File 'lib/i18n_admin/export/xls.rb', line 53

def save
  spreadsheet.write(file_path)

  source = File.open(file_path, 'rb')
  self.export_file = ExportFile.create!(job_id: job_id, file: source)
ensure
  if defined?(source) && source
    source.close
    File.unlink(source.path)
  end
end