Class: WebTranslateIt::TranslationFile

Inherits:
Object
  • Object
show all
Defined in:
lib/web_translate_it/translation_file.rb

Overview

A TranslationFile is the representation of a master language file on Web Translate It.

This class allows to manipulate TranslationFiles, more specifically upload and download them. If you pass a Locale to the master language file you will be able to manipulate a target language file.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(id, file_path, locale, api_key, updated_at = nil, remote_checksum = '', master_id = nil, fresh = nil) ⇒ TranslationFile

rubocop:todo Metrics/ParameterLists



15
16
17
18
19
20
21
22
23
24
# File 'lib/web_translate_it/translation_file.rb', line 15

def initialize(id, file_path, locale, api_key, updated_at = nil, remote_checksum = '', master_id = nil, fresh = nil) # rubocop:todo Metrics/ParameterLists
  self.id         = id
  self.file_path  = file_path
  self.locale     = locale
  self.api_key    = api_key
  self.updated_at = updated_at
  self.remote_checksum = remote_checksum
  self.master_id  = master_id
  self.fresh      = fresh
end

Instance Attribute Details

#api_keyObject

rubocop:todo Metrics/ClassLength



13
14
15
# File 'lib/web_translate_it/translation_file.rb', line 13

def api_key
  @api_key
end

#file_pathObject

rubocop:todo Metrics/ClassLength



13
14
15
# File 'lib/web_translate_it/translation_file.rb', line 13

def file_path
  @file_path
end

#freshObject

rubocop:todo Metrics/ClassLength



13
14
15
# File 'lib/web_translate_it/translation_file.rb', line 13

def fresh
  @fresh
end

#idObject

rubocop:todo Metrics/ClassLength



13
14
15
# File 'lib/web_translate_it/translation_file.rb', line 13

def id
  @id
end

#localeObject

rubocop:todo Metrics/ClassLength



13
14
15
# File 'lib/web_translate_it/translation_file.rb', line 13

def locale
  @locale
end

#master_idObject

rubocop:todo Metrics/ClassLength



13
14
15
# File 'lib/web_translate_it/translation_file.rb', line 13

def master_id
  @master_id
end

#remote_checksumObject

rubocop:todo Metrics/ClassLength



13
14
15
# File 'lib/web_translate_it/translation_file.rb', line 13

def remote_checksum
  @remote_checksum
end

#updated_atObject

rubocop:todo Metrics/ClassLength



13
14
15
# File 'lib/web_translate_it/translation_file.rb', line 13

def updated_at
  @updated_at
end

Instance Method Details

#create(http_connection) ⇒ Object

Create a master language file to Web Translate It by performing a POST Request.

Example of implementation:

configuration = WebTranslateIt::Configuration.new
file = TranslationFile.new(nil, file_path, nil, configuration.api_key)
file.create # should respond the HTTP code 201 Created

Note that the request might or might not eventually be acted upon, as it might be disallowed when processing actually takes place. This is due to the fact that language file imports are handled by background processing.



151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# File 'lib/web_translate_it/translation_file.rb', line 151

def create(http_connection) # rubocop:todo Metrics/AbcSize, Metrics/MethodLength
  success = true
  tries ||= 3
  display = []
  display.push file_path
  display.push "#{StringUtil.checksumify(local_checksum.to_s)}..[     ]"
  if File.exist?(file_path)
    File.open(file_path) do |file|
      params = [['name', file_path]]
      params += [['file', file]]
      request = Net::HTTP::Post.new(api_url_for_create)
      WebTranslateIt::Util.add_fields(request)
      request.set_form params, 'multipart/form-data'
      display.push Util.handle_response(http_connection.request(request))
      puts StringUtil.array_to_columns(display)
    rescue Timeout::Error
      puts StringUtil.failure('Request timeout. Will retry in 5 seconds.')
      if (tries -= 1).positive?
        sleep(5)
        retry
      else
        success = false
      end
    rescue StandardError
      display.push StringUtil.failure("An error occured: #{$ERROR_INFO}")
      success = false
    end
  else
    puts StringUtil.failure("\nFile #{file_path} doesn't exist locally!")
  end
  success
end

#delete(http_connection) ⇒ Object

Delete a master language file from Web Translate It by performing a DELETE Request.



186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# File 'lib/web_translate_it/translation_file.rb', line 186

def delete(http_connection) # rubocop:todo Metrics/AbcSize, Metrics/MethodLength
  success = true
  tries ||= 3
  display = []
  display.push file_path
  if File.exist?(file_path)
    begin
      request = Net::HTTP::Delete.new(api_url_for_delete)
      WebTranslateIt::Util.add_fields(request)
      display.push Util.handle_response(http_connection.request(request))
      puts StringUtil.array_to_columns(display)
    rescue Timeout::Error
      puts StringUtil.failure('Request timeout. Will retry in 5 seconds.')
      if (tries -= 1).positive?
        sleep(5)
        retry
      else
        success = false
      end
    rescue StandardError
      display.push StringUtil.failure("An error occured: #{$ERROR_INFO}")
      success = false
    end
  else
    puts StringUtil.failure("\nMaster file #{file_path} doesn't exist locally!")
  end
  success
end

#exists?Boolean

Returns:

  • (Boolean)


215
216
217
# File 'lib/web_translate_it/translation_file.rb', line 215

def exists?
  File.exist?(file_path)
end

#fetch(http_connection, force = false) ⇒ Object

Fetch a language file. By default it will make a conditional GET Request, using the ‘If-Modified-Since` tag. You can force the method to re-download your file by passing `true` as a second argument

Example of implementation:

configuration = WebTranslateIt::Configuration.new
file = configuration.files.first
file.fetch # the first time, will return the content of the language file with a status 200 OK
file.fetch # returns nothing, with a status 304 Not Modified
file.fetch(true) # force to re-download the file, will return the content of the file with a 200 OK


38
39
40
41
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
72
73
74
75
# File 'lib/web_translate_it/translation_file.rb', line 38

def fetch(http_connection, force = false) # rubocop:todo Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/MethodLength, Metrics/PerceivedComplexity
  success = true
  tries ||= 3
  display = []
  if fresh
    display.push(file_path)
  else
    display.push("*#{file_path}")
  end
  display.push "#{StringUtil.checksumify(local_checksum.to_s)}..#{StringUtil.checksumify(remote_checksum.to_s)}"
  if !File.exist?(file_path) || force || (remote_checksum != local_checksum)
    begin
      request = Net::HTTP::Get.new(api_url)
      WebTranslateIt::Util.add_fields(request)
      FileUtils.mkpath(file_path.split('/')[0..-2].join('/')) unless File.exist?(file_path) || (file_path.split('/')[0..-2].join('/') == '')
      begin
        response = http_connection.request(request)
        File.open(file_path, 'wb') { |file| file << response.body } if response.code.to_i == 200
        display.push Util.handle_response(response)
      rescue Timeout::Error
        puts StringUtil.failure('Request timeout. Will retry in 5 seconds.')
        if (tries -= 1).positive?
          sleep(5)
          retry
        else
          success = false
        end
      rescue StandardError
        display.push StringUtil.failure("An error occured: #{$ERROR_INFO}")
        success = false
      end
    end
  else
    display.push StringUtil.success('Skipped')
  end
  print StringUtil.array_to_columns(display)
  success
end

#modified_remotely?Boolean

Returns:

  • (Boolean)


219
220
221
# File 'lib/web_translate_it/translation_file.rb', line 219

def modified_remotely?
  fetch == '200 OK'
end

#upload(http_connection, merge = false, ignore_missing = false, label = nil, minor_changes = false, force = false, rename_others = false, destination_path = nil) ⇒ Object

Update a language file to Web Translate It by performing a PUT Request.

Example of implementation:

configuration = WebTranslateIt::Configuration.new
locale = configuration.locales.first
file = configuration.files.first
file.upload # should respond the HTTP code 202 Accepted

Note that the request might or might not eventually be acted upon, as it might be disallowed when processing actually takes place. This is due to the fact that language file imports are handled by background processing. rubocop:todo Metrics/PerceivedComplexity rubocop:todo Metrics/ParameterLists rubocop:todo Metrics/MethodLength rubocop:todo Metrics/AbcSize



92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/web_translate_it/translation_file.rb', line 92

def upload(http_connection, merge = false, ignore_missing = false, label = nil, minor_changes = false, force = false, rename_others = false, destination_path = nil) # rubocop:todo Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/MethodLength, Metrics/ParameterLists, Metrics/PerceivedComplexity
  success = true
  tries ||= 3
  display = []
  display.push(file_path)
  display.push "#{StringUtil.checksumify(local_checksum.to_s)}..#{StringUtil.checksumify(remote_checksum.to_s)}"
  if File.exist?(file_path)
    if force || (remote_checksum != local_checksum)
      File.open(file_path) do |file|
        params = [
          ['merge', merge.to_s],
          ['ignore_missing', ignore_missing.to_s],
          ['label', label.to_s],
          ['minor_changes', minor_changes.to_s],
          ['rename_others', rename_others.to_s],
          ['file', file]
        ]
        params += [['name', destination_path]] unless destination_path.nil?
        request = Net::HTTP::Put.new(api_url)
        WebTranslateIt::Util.add_fields(request)
        request.set_form params, 'multipart/form-data'
        display.push Util.handle_response(http_connection.request(request))
      rescue Timeout::Error
        puts StringUtil.failure('Request timeout. Will retry in 5 seconds.')
        if (tries -= 1).positive? # rubocop:todo Metrics/BlockNesting
          sleep(5)
          retry
        else
          success = false
        end
      rescue StandardError
        display.push StringUtil.failure("An error occured: #{$ERROR_INFO}")
        success = false
      end
    else
      display.push StringUtil.success('Skipped')
    end
    puts StringUtil.array_to_columns(display)
  else
    puts StringUtil.failure("Can't push #{file_path}. File doesn't exist locally.")
  end
  success
end