Created
June 24, 2015 12:20
-
-
Save nikz/02f6abc710a360955f8f to your computer and use it in GitHub Desktop.
Code for the Minimum Viable API Client (https://gelato.io/blog/minimum-viable-ruby-api-client-with-invoiced-and-httparty)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class InvoiceGeneratorClient | |
PDF_CONTENT_TYPE = "application/pdf" | |
JSON_CONTENT_TYPE = "application/json" | |
include HTTParty | |
base_uri "https://invoice-generator.com" | |
class << self | |
def create_invoice(filename, options = {}) | |
response = post("/", body: options.to_json, headers: { "Content-Type" => JSON_CONTENT_TYPE }) | |
if response.success? && response.content_type == PDF_CONTENT_TYPE | |
save_pdf(filename, response.parsed_response) | |
else | |
# something has gone horribly wrong! | |
end | |
end | |
private | |
def save_pdf(filename, data) | |
File.open(filename, "wb+") do |f| | |
f << data | |
end | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def generate_invoice | |
InvoiceGeneratorClient.create_invoice( | |
Rails.root.join("tmp", "invoice-#{id}.pdf"), | |
from: "My Company, Inc ®", | |
to: customer_name, | |
logo: "http://placekitten.com/320/140", | |
number: id, | |
date: created_at.to_date.to_s, | |
items: [ | |
{ | |
name: description, | |
quantity: 1, | |
unit_cost: self.amount_in_cents / 100.0 | |
} | |
], | |
notes: "Thank you so much for your business!" | |
) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment