Class: Huckleberry::Import::Downloader

Inherits:
Object
  • Object
show all
Defined in:
lib/huckleberry/import/downloader.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(directory = "tmp/usda", version = "sr27") ⇒ Downloader

Returns a new instance of Downloader.



8
9
10
11
# File 'lib/huckleberry/import/downloader.rb', line 8

def initialize(directory = "tmp/usda", version = "sr27")
  @directory = directory
  @version = version
end

Instance Attribute Details

#directoryObject (readonly)

Returns the value of attribute directory.



6
7
8
# File 'lib/huckleberry/import/downloader.rb', line 6

def directory
  @directory
end

#versionObject (readonly)

Returns the value of attribute version.



6
7
8
# File 'lib/huckleberry/import/downloader.rb', line 6

def version
  @version
end

Instance Method Details

#cleanupObject



13
14
15
# File 'lib/huckleberry/import/downloader.rb', line 13

def cleanup
  FileUtils.rm_rf(directory)
end

#connectionObject



46
47
48
# File 'lib/huckleberry/import/downloader.rb', line 46

def connection
  @connection ||= Faraday.new(url: "https://www.ars.usda.gov")
end

#downloadObject



27
28
29
30
31
32
33
34
# File 'lib/huckleberry/import/downloader.rb', line 27

def download
  unless File.directory?(directory)
    FileUtils.mkdir_p("#{directory}/#{version}")
  end
  File.open("#{directory}/#{version}.zip", "w+b") do |file|
    file.write connection.get(final_path).body
  end
end

#download_and_unzipObject



17
18
19
# File 'lib/huckleberry/import/downloader.rb', line 17

def download_and_unzip
  download and unzip
end

#final_pathObject



50
51
52
53
54
55
56
57
58
# File 'lib/huckleberry/import/downloader.rb', line 50

def final_path
  look_ahead = connection.head(path)
  if look_ahead.status == 302
    raise "No Location" unless look_ahead.headers["location"]
    URI.parse(look_ahead.headers["location"]).path
  else
    path
  end
end

#pathObject



21
22
23
24
25
# File 'lib/huckleberry/import/downloader.rb', line 21

def path
  [
    "SP2UserFiles", "Place", "12354500", "Data", version.upcase, "dnload", "#{version_file}.zip"
  ].join("/")
end

#unzipObject



36
37
38
39
40
41
42
43
44
# File 'lib/huckleberry/import/downloader.rb', line 36

def unzip
  Zip::File.open("#{directory}/#{version}.zip") do |zipfile|
    zipfile.each do |file|
      unless File.exist?("#{directory}/#{version}/#{file.name}")
        zipfile.extract(file, "#{directory}/#{version}/#{file.name}")
      end
    end
  end
end

#version_fileObject



60
61
62
63
64
65
66
67
# File 'lib/huckleberry/import/downloader.rb', line 60

def version_file
  case @version
  when "sr27"
    "sr27asc"
  else
    @version
  end
end