class MetallicaLogo::Client
HTTP client for requesting logo generation and also if desired, downloading to a local destination
Constants
- MAX_CHARACTERS
Attributes
base_url[R]
rest_klass[R]
Public Class Methods
new(base_url: MetallicaLogo::BASE_URL, rest_klass: RestClient)
click to toggle source
# File lib/metallica_logo/client.rb, line 11 def initialize(base_url: MetallicaLogo::BASE_URL, rest_klass: RestClient) @rest_klass = rest_klass @base_url = base_url end
Public Instance Methods
generate_and_download_logo(text, destination_file)
click to toggle source
# File lib/metallica_logo/client.rb, line 25 def generate_and_download_logo(text, destination_file) result = generate_logo(text) destination_file = Pathname(destination_file) destination_file.dirname.mkpath response = download(result.file) IO.binwrite(destination_file, response.body) destination_file end
generate_logo(text)
click to toggle source
# File lib/metallica_logo/client.rb, line 16 def generate_logo(text) if text.size > MAX_CHARACTERS raise RequestError, "Too many characters, limit is #{MAX_CHARACTERS}" end response = post("#{@base_url}/creation/", 'the_text': text) MetallicaLogo::Result.new(JSON.parse(response)) end
Private Instance Methods
download(url)
click to toggle source
# File lib/metallica_logo/client.rb, line 36 def download(url) rest_klass.get(url) rescue rest_klass::ExceptionWithResponse => e validate_response(e.response) end
post(url, payload)
click to toggle source
# File lib/metallica_logo/client.rb, line 42 def post(url, payload) response = rest_klass.post(url, payload) validate_response(response) rescue rest_klass::ExceptionWithResponse => e validate_response(e.response) end
valid_json?(value)
click to toggle source
# File lib/metallica_logo/client.rb, line 62 def valid_json?(value) result = JSON.parse(value) result.is_a?(Hash) rescue JSON::ParserError false end
validate_response(response)
click to toggle source
# File lib/metallica_logo/client.rb, line 49 def validate_response(response) unless valid_json?(response.body) raise ServerError, 'Invalid JSON returned' end case response.code.to_s when /2\d\d/ then response when /5\d\d/ then raise ServerError, response.body else raise RequestError, response.body end end