Class: OpenRecycling::Documents::Uploads
- Defined in:
- lib/open_recycling/documents/uploads.rb
Instance Attribute Summary
Attributes inherited from Resource
#api_url, #jwt_token, #root_node_plural, #root_node_singular
Instance Method Summary collapse
- #create(file_path:, mime_type:, organization_id:, issued_by_organization_id: nil) ⇒ Object
-
#initialize(base_url: nil, jwt_token: nil) ⇒ Uploads
constructor
A new instance of Uploads.
Methods inherited from Resource
#all, #destroy, #ensure_supported_method, #find, only, supported_methods, #update
Constructor Details
#initialize(base_url: nil, jwt_token: nil) ⇒ Uploads
Returns a new instance of Uploads.
8 9 10 11 12 13 14 15 |
# File 'lib/open_recycling/documents/uploads.rb', line 8 def initialize(base_url: nil, jwt_token: nil) super( root_node_singular: "upload", root_node_plural: "uploads", api_url: "#{base_url}/uploads", jwt_token: jwt_token ) end |
Instance Method Details
#create(file_path:, mime_type:, organization_id:, issued_by_organization_id: nil) ⇒ Object
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/open_recycling/documents/uploads.rb', line 17 def create(file_path:, mime_type:, organization_id:, issued_by_organization_id: nil) uri = URI(api_url) # Prepare the file and boundary boundary = "----Upload#{rand(1000000)}" file = File.open(file_path, 'rb') file_content = file.read # Prepare multipart body post_body = [] post_body << "--#{boundary}\r\n" post_body << "Content-Disposition: form-data; name=\"upload[file]\"; filename=\"#{File.basename(file_path)}\"\r\n" post_body << "Content-Type: #{mime_type}\r\n\r\n" post_body << file_content post_body << "\r\n" # Add the `upload[organizationId]` part post_body << "--#{boundary}\r\n" post_body << "Content-Disposition: form-data; name=\"upload[issuedToOrganizationId]\"\r\n\r\n" post_body << organization_id.to_s post_body << "\r\n" if issued_by_organization_id # Add the `upload[issuedByOrganizationId]` part post_body << "--#{boundary}\r\n" post_body << "Content-Disposition: form-data; name=\"upload[issuedByOrganizationId]\"\r\n\r\n" post_body << issued_by_organization_id.to_s post_body << "\r\n" end post_body << "--#{boundary}--\r\n" # Create and send the POST request http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = (uri.scheme == 'https') request = Net::HTTP::Post.new(uri.path) request['Content-Type'] = "multipart/form-data; boundary=#{boundary}" request["Authorization"] = "Bearer #{jwt_token}" request["Accept"] = "application/json" request.body = post_body.join # Execute the request and get the response response = http.request(request) if response.is_a?(Net::HTTPSuccess) parse_resource(response.body) else handle_error(response) end end |