Sha256: 3731b2e094c3c927ba518b021cce1fb41b76526e66753e789626edf6c2279e71

Contents?: true

Size: 1.33 KB

Versions: 6

Compression:

Stored size: 1.33 KB

Contents

module Bearcat
  class Client < Footrest::Client
    module CanvasFiles

      def upload_file(api_path, file_path, params = {})
        declare_response = declare_file(api_path, file_params(file_path).merge(params))
        confirmation_url = post_file(declare_response['upload_url'], declare_response['upload_params'], file_path)
        confirm_file_upload(confirmation_url)
      end

      private

      def file_params(file_path)
        {
          size: File.open(file_path).size,
          name: File.basename(file_path)
        }
      end

      def declare_file(api_path, params)
        post(api_path, params)
      end

      def post_file(url, params, file_path)
        params['Filename'] = File.basename(file_path)
        params['file'] = Faraday::UploadIO.new(file_path, params['content-type'])

        response = upload_connection.post(url, params)
        if response.status == (302 || 303) #success if it is a redirect
          response.headers['Location']
        else
          raise 'FailedFileUpload'
        end
      end

      def confirm_file_upload(url)
        uri = URI(url)
        post(uri.path, CGI::parse(uri.query))
      end

      def upload_connection
        Faraday.new do |f|
          f.request :multipart
          f.request :url_encoded
          f.adapter :net_http
        end
      end

    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
bearcat-0.9.17 lib/bearcat/client/canvas_files.rb
bearcat-0.9.16 lib/bearcat/client/canvas_files.rb
bearcat-0.9.15 lib/bearcat/client/canvas_files.rb
bearcat-0.9.14 lib/bearcat/client/canvas_files.rb
bearcat-0.9.13 lib/bearcat/client/canvas_files.rb
bearcat-0.9.12 lib/bearcat/client/canvas_files.rb