class Pixaven::Response

Builds an object containing response data

Public Class Methods

new(object, save_path: nil) click to toggle source
# File lib/pixaven/response.rb, line 7
def initialize(object, save_path: nil)
    @object = object
    @save_path = save_path
    fetch_metadata
    return unless @error.nil?

    binary_response if binary?
end

Public Instance Methods

data() click to toggle source
# File lib/pixaven/response.rb, line 16
def data
    result = [@error, @metadata]
    result << @file if binary? && @save_path.nil? && @file
    result
end

Private Instance Methods

binary?() click to toggle source
# File lib/pixaven/response.rb, line 24
def binary?
    !@object.headers[:x_pixaven_meta].nil?
end
binary_response() click to toggle source

Handles binary response and saves the file or stores it as a buffer

# File lib/pixaven/response.rb, line 51
def binary_response
    return save_file if @save_path
    @file = @object.body
end
fetch_metadata() click to toggle source

Extracts the metadata either from the response body or X-Pixaven-Meta header if the binary response was in use

# File lib/pixaven/response.rb, line 33
def fetch_metadata
    data = JSON.parse(@object.headers[:x_pixaven_metadata] || @object.body)

    if data["success"]
        @metadata = data
    else
        @error = data["message"]
    end
rescue JSON::ParserError
    @error = "Unable to parse JSON response from "
    @error += (binary? ? "X-Pixaven-Meta header" : "the Pixaven Image API")
end
save_file() click to toggle source

Saves binary response to disk

# File lib/pixaven/response.rb, line 60
def save_file
    @file = File.open(@save_path, "wb")
    @file.write(@object.body)
    @file.close
rescue
    @error = "Unable to save resulting image at `#{@save_path}` location"
end