Skip to content

Instantly share code, notes, and snippets.

@sunny
Last active January 3, 2016 16:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sunny/8492225 to your computer and use it in GitHub Desktop.
Save sunny/8492225 to your computer and use it in GitHub Desktop.
# Access makexyz.com's API to POST a design.
# http://www.makexyz.com/developers
#
# # Usage with Rails
#
# Add `gem "rest-client"` in your `Gemfile`.
#
# Place this file in your Rails' `lib` directory.
#
# Create a `config/initializers/makexyz.rb`:
#
# require "makexyz"
# ENV['MAKEXYZ_KEY'] = "yourkey"
#
# Use it in your controllers like this:
#
# file = File.open("design.stl")
# upload = Makexyz::Upload.new(file)
# if upload.send
# redirect_to upload.url
# else
# redirect_to :back, upload.error
# end
#
module Makexyz
class Upload
attr_reader :url, :error
def initialize(file)
@file = file
end
def send
key = ENV['MAKEXYZ_KEY'] or fail "Missing ENV['MAKEXYZ_KEY']"
url = "http://www.makexyz.com/api/upload_design?api_key=#{key}"
response = RestClient::Request.execute(
method: :post,
url: url,
payload: { file: @file },
# Disable file timeout option
# Depending on your configuration, you can try one or the other.
timeout: -1,
#open_timeout: -1
)
json = JSON.parse(response)
if json["success"]
@url = json["url"]
true
else
@error = json["error"]
false
end
end
end
end
require 'spec_helper'
describe Makexyz::Upload do
before do
ENV['MAKEXYZ_KEY'] = "testkey"
end
let(:file) { double(:file) }
let(:json) { double(:file) }
it "uploads a design" do
allow(RestClient::Request).to receive(:execute) {
'{"success":true, "url":"http://example.org"}'
}
upload = Makexyz::Upload.new(file)
expect(upload.send).to be_true
expect(upload.url).to eq("http://example.org")
expect(RestClient::Request).to have_received(:execute).with(
method: :post,
url: "http://www.makexyz.com/api/upload_design?api_key=testkey",
payload: { file: file },
timeout: -1
)
end
it "stores errors" do
allow(RestClient::Request).to receive(:execute) {
'{"success":false, "error":"Some kind of error"}'
}
upload = Makexyz::Upload.new(file)
expect(upload.send).to be_false
expect(upload.url).to be_nil
expect(upload.error).to eq("Some kind of error")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment