Sha256: 8da5d24b0cc4c3b0696f429732d91c038f95a4950bfb3756247bdd5ceb5fd8b5

Contents?: true

Size: 1.5 KB

Versions: 6

Compression:

Stored size: 1.5 KB

Contents

require 'zip'

module UsdaNutrientDatabase
  module Import
    class Downloader

      attr_reader :directory, :version

      def initialize(directory = 'tmp/usda', version = 'sr25')
        @directory = directory
        @version = version
      end

      def cleanup
        UsdaNutrientDatabase.log 'Cleaning up data'
        FileUtils.rm_rf(directory)
      end

      def download_and_unzip
        download and unzip
      end

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

      def download
        UsdaNutrientDatabase.log "Downloading USDA data version: #{version}"
        unless File.directory?(directory)
          FileUtils.mkdir_p("#{directory}/#{version}")
        end
        File.open("#{directory}/#{version}.zip", 'w+b') do |file|
          file.write connection.get(path).body
        end
      end

      def unzip
        UsdaNutrientDatabase.log 'Unzipping data'
        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

      def connection
        @connection ||= Faraday.new(url: 'http://www.ars.usda.gov') do |faraday|
          faraday.response :logger
          faraday.adapter Faraday.default_adapter
        end
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
usda-nutrient-database-0.4.0 lib/usda_nutrient_database/import/downloader.rb
usda-nutrient-database-0.3.0 lib/usda_nutrient_database/import/downloader.rb
usda-nutrient-database-0.2.0 lib/usda_nutrient_database/import/downloader.rb
usda-nutrient-database-0.1.2 lib/usda_nutrient_database/import/downloader.rb
usda-nutrient-database-0.1.1 lib/usda_nutrient_database/import/downloader.rb
usda-nutrient-database-0.1.0 lib/usda_nutrient_database/import/downloader.rb