Class: Imgurz::Client

Inherits:
Struct
  • Object
show all
Defined in:
lib/imgurz/client.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#keyObject

Returns the value of attribute key

Returns:

  • (Object)

    the current value of key



8
9
10
# File 'lib/imgurz/client.rb', line 8

def key
  @key
end

Instance Method Details

#as_anonymousObject



10
11
12
13
# File 'lib/imgurz/client.rb', line 10

def as_anonymous
  @method = 'anonymous'
  self
end

#as_regsiteredObject



15
16
17
18
# File 'lib/imgurz/client.rb', line 15

def as_regsitered
  @method = 'registered'
  self
end

#into(album_id) ⇒ Object



20
21
22
23
# File 'lib/imgurz/client.rb', line 20

def into(album_id)
  @album_id = album_id
  self
end

#upload(image) ⇒ Object



25
26
27
28
# File 'lib/imgurz/client.rb', line 25

def upload(image)
  return self.upload_file(image) if image.kind_of?(File) # already a file
  self.upload_file_at(image) # we assume that a path is given 
end

#upload_file(file) ⇒ Object



37
38
39
40
41
# File 'lib/imgurz/client.rb', line 37

def upload_file(file)
  return false unless file.kind_of?(File)
  content = [file.read].pack('m')
  self.upload_image_content(content)
end

#upload_file_at(file_path) ⇒ Object



30
31
32
33
34
35
# File 'lib/imgurz/client.rb', line 30

def upload_file_at(file_path)
  return false unless file_path.kind_of?(String)
  File.open(file_path, 'rb') { |file|
    return self.upload_file(file)
  }
end

#upload_image_content(file_content) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/imgurz/client.rb', line 43

def upload_image_content(file_content)
  return false unless file_content.kind_of?(String)
  uri = URI.parse Imgurz::UPLOAD_ENDPOINT
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  request = Net::HTTP::Post.new uri.path
  self.as_anonymous unless @method
  request['Authorization'] = "Client-ID #{key}" if @method=='anonymous'
  request['Authorization'] = "Bearer #{key}" if @method=='registered'
  data = {image:file_content}
  data[:album] = @album_id if @album_id
  request.set_form_data(data)
  response = http.request(request)
  JSON.parse response.body
end