Method: WebTranslateIt::TranslationFile#fetch
- Defined in:
- lib/web_translate_it/translation_file.rb
#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 |