Class: Base::Endpoints::Images

Inherits:
Base::Endpoint show all
Defined in:
lib/base/endpoints/images.rb

Overview

This endpoint contains methods for uploading and managing images.

Instance Attribute Summary

Attributes inherited from Base::Endpoint

#connection, #path

Instance Method Summary collapse

Methods inherited from Base::Endpoint

#io, #parse, #request

Constructor Details

#initialize(access_token:, url:) ⇒ Images

Initializes this endpoint.



8
9
10
11
# File 'lib/base/endpoints/images.rb', line 8

def initialize(access_token:, url:)
  @path = 'images'
  super
end

Instance Method Details

#create(path:, type:, filename:) ⇒ Object

Uploads the given image and returns its metadata.

Only images with ImageMagick understands can be uploaded otherwise it will raise an error.



17
18
19
20
21
22
23
24
25
26
27
# File 'lib/base/endpoints/images.rb', line 17

def create(path:, type:, filename:)
  request do
    io =
      Faraday::UploadIO.new(path, type, filename)

    response =
      connection.post('', 'image' => io)

    parse(response.body)
  end
end

#delete(id) ⇒ Object

Deletes the image with the given ID.



83
84
85
86
87
88
89
90
# File 'lib/base/endpoints/images.rb', line 83

def delete(id)
  request do
    response =
      connection.delete id

    parse(response.body)
  end
end

#download(id, quality: nil, resize: nil, format: nil, crop: nil) ⇒ Object

Downloads the image with the given ID.

It is possible to crop and resize the image and change its format and quality.



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/base/endpoints/images.rb', line 52

def download(id,
             quality: nil,
             resize: nil,
             format: nil,
             crop: nil)
  url =
    image_url(id, quality: quality,
                  resize: resize,
                  format: format,
                  crop: crop)

  response =
    Faraday.new(url) do |conn|
      conn.use RaiseError
      conn.use Faraday::Adapter::NetHttp
    end.get

  io(response.body)
end

#get(id) ⇒ Object

Returns the metadata of the image with the given ID.



73
74
75
76
77
78
79
80
# File 'lib/base/endpoints/images.rb', line 73

def get(id)
  request do
    response =
      connection.get id

    parse(response.body)
  end
end

#image_url(id, quality: nil, resize: nil, format: nil, crop: nil) ⇒ Object

Returns the image url of the image with the given ID.

It is possible to crop and resize the image and change its format and quality.



33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/base/endpoints/images.rb', line 33

def image_url(id,
              quality: nil,
              resize: nil,
              format: nil,
              crop: nil)
  params = {}

  quality && params[:quality] = quality.to_s
  format && params[:format] = format.to_s
  resize && params[:resize] = resize.to_s
  crop && params[:crop] = crop.to_s

  "#{connection.url_prefix}#{id}/version?#{URI.encode_www_form(params)}"
end