Class: Uploader::Upload

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby-uploader/uploader.rb

Defined Under Namespace

Classes: Put

Instance Method Summary collapse

Constructor Details

#initialize(url, path, headers = nil) ⇒ Upload

Returns a new instance of Upload.



6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/ruby-uploader/uploader.rb', line 6

def initialize(url, path, headers = nil)
  @url = url
  @headers  = headers
  @path     = path
  @response = nil
  @handlers = {
    before:       [],
    after:        [],
    before_chunk: [],
    after_chunk:  []
  }
end

Instance Method Details

#add_handler(phase, handler) ⇒ Object



42
43
44
45
# File 'lib/ruby-uploader/uploader.rb', line 42

def add_handler(phase, handler)
  fail "Handler phase #{phase} does not exists" unless @handlers.key? phase
  @handlers[phase] << handler
end

#executeObject



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/ruby-uploader/uploader.rb', line 19

def execute
  Net::HTTP.start(@url.host, @url.port, use_ssl: @url.scheme == 'https') do |http|

    headers = @headers ? default_headers.merge(@headers) : default_headers

    request = Put.new(@url, headers, @handlers).tap do |r|
      r.body_stream = File.open(@path)
    end

    @handlers[:before].each do |handler|
      handler.execute request
    end

    @response = http.request(request)

    @handlers[:after].each do |handler|
      handler.execute @response
    end

    @response
  end
end