Method: GoodData::Rest::Connection#download

Defined in:
lib/gooddata/rest/connection.rb

#download(what, where, options = {}) ⇒ Object

Parameters:

  • what

    Address of the remote file.

  • where

    Full path to the target file.

  • [Bool] (Hash)

    a customizable set of options



263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
# File 'lib/gooddata/rest/connection.rb', line 263

def download(what, where, options = {})
  # handle the path (directory) given in what
  ilast_slash = what.rindex('/')
  if ilast_slash.nil?
    what_dir = ''
  else
    # take the directory from the path
    what_dir = what[0..ilast_slash - 1]
    # take the filename from the path
    what = what[ilast_slash + 1..-1]
  end

  option_dir = options[:directory] || ''
  option_dir = option_dir[0..-2] if option_dir[-1] == '/'

  # join the otion dir with the what_dir
  # [option dir empty, what dir empty] => the joined dir
  dir_hash = {
    [true, true] => '',
    [true, false] => what_dir,
    [false, true] => option_dir,
    [false, false] => "#{what_dir}/#{option_dir}"
  }
  dir = dir_hash[[option_dir.empty?, what_dir.empty?]]

  staging_uri = options[:staging_url].to_s

  base_url = dir.empty? ? staging_uri : URI.join("#{server}", staging_uri, "#{dir}/").to_s
  sanitized_what = options[:url_encode] == false ? what : CGI.escape(what)
  url = URI.join("#{server}", base_url, sanitized_what).to_s

  b = proc do |f|
    raw = {
      :headers => @webdav_headers.merge(:x_gdc_authtt => headers[:x_gdc_authtt]),
      :method => :get,
      :url => url,
      :verify_ssl => verify_ssl
    }
    RestClient::Request.execute(raw) do |chunk, _x, response|
      if response.code.to_s == '202'
        fail RestRetryError, 'Got 202, retry'
      elsif response.code.to_s != '200'
        fail ArgumentError, "Error downloading #{url}. Got response: #{response.code} #{response} #{response.body}"
      end
      f.write chunk
    end
  end

  GoodData::Rest::Connection.retryable(:tries => Helpers::GD_MAX_RETRY, :refresh_token => proc { refresh_token }, :on => RestRetryError) do
    if where.is_a?(IO) || where.is_a?(StringIO)
      b.call(where)
    else
      # Assume it is a string or file
      File.open(where, 'w') do |f|
        b.call(f)
      end
    end
  end
end