Class: YourImageShare::Client

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

Overview

Talks to the YourImageShare upload API. Create one with YourImageShare::Client.new(api_key). Get a key from the API tab at https://yourimageshare.com/my-account.

Instance Method Summary collapse

Constructor Details

#initialize(api_key, base_url: DEFAULT_BASE_URL, timeout: 30) ⇒ Client

Returns a new instance of Client.

Raises:

  • (ArgumentError)


12
13
14
15
16
17
18
# File 'lib/yourimageshare/client.rb', line 12

def initialize(api_key, base_url: DEFAULT_BASE_URL, timeout: 30)
  raise ArgumentError, "api_key is required" if api_key.nil? || api_key.empty?

  @api_key = api_key
  @base_url = base_url
  @timeout = timeout
end

Instance Method Details

#delete(id) ⇒ Object

Removes one of your uploads by id. Raises APIError on failure.



59
60
61
62
63
64
65
66
# File 'lib/yourimageshare/client.rb', line 59

def delete(id)
  uri = URI("#{@base_url}/#{URI.encode_www_form_component(id)}")
  request = Net::HTTP::Delete.new(uri)
  set_common_headers(request)

  execute(uri, request)
  nil
end

#list(page = nil) ⇒ Object

Returns your uploads, newest first, 50 per page. page < 2 fetches the first page.



48
49
50
51
52
53
54
55
56
# File 'lib/yourimageshare/client.rb', line 48

def list(page = nil)
  uri = URI(@base_url)
  uri.query = URI.encode_www_form(page: page) if page && page > 1

  request = Net::HTTP::Get.new(uri)
  set_common_headers(request)

  ListResult.from_json(execute(uri, request))
end

#upload(file_path, expires_in: nil) ⇒ Object

Uploads a local file by path. expires_in (seconds, 60 to 2,592,000 = 30 days) auto-deletes the upload later; nil means a permanent upload.



22
23
24
25
26
# File 'lib/yourimageshare/client.rb', line 22

def upload(file_path, expires_in: nil)
  File.open(file_path, "rb") do |f|
    upload_io(f, File.basename(file_path), expires_in: expires_in)
  end
end

#upload_io(io, filename, expires_in: nil) ⇒ Object

Uploads from any IO-like object (must respond to #read). filename should include a real extension so the server can infer content type.



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/yourimageshare/client.rb', line 30

def upload_io(io, filename, expires_in: nil)
  uri = URI(@base_url)
  request = Net::HTTP::Post.new(uri)
  set_common_headers(request)

  form = [["uploads", io, { filename: filename }]]
  form << ["expires_in", expires_in.to_s] if expires_in && expires_in > 0
  # Net::HTTP streams IO form values in chunks rather than buffering
  # the whole file into memory - important since uploads can be up to
  # 200MB (video).
  request.set_form(form, "multipart/form-data")

  body = execute(uri, request)
  UploadResult.from_json(body["data"] || {})
end