Module: FmRest::V1::ContainerFields
- Included in:
- FmRest::V1
- Defined in:
- lib/fmrest/v1/container_fields.rb
Constant Summary collapse
- DEFAULT_UPLOAD_CONTENT_TYPE =
"application/octet-stream".freeze
Instance Method Summary collapse
-
#fetch_container_data(container_field_url) ⇒ IO
Given a container field URL it tries to fetch it and returns an IO object with its body content (see Ruby's OpenURI for how the IO object is extended with useful HTTP response information).
-
#upload_container_data(connection, container_path, filename_or_io, options = {}) ⇒ Object
Handles the core logic of uploading a file into a container field.
Instance Method Details
#fetch_container_data(container_field_url) ⇒ IO
Given a container field URL it tries to fetch it and returns an IO object with its body content (see Ruby's OpenURI for how the IO object is extended with useful HTTP response information).
This method uses Net::HTTP and OpenURI instead of Faraday.
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 |
# File 'lib/fmrest/v1/container_fields.rb', line 18 def fetch_container_data(container_field_url) require "open-uri" begin url = URI(container_field_url) rescue ::URI::InvalidURIError raise FmRest::ContainerFieldError, "Invalid container field URL `#{container_field_url}'" end # Make sure we don't try to open anything on the file:/ URI scheme unless url.scheme.match(/\Ahttps?\Z/) raise FmRest::ContainerFieldError, "Container URL is not HTTP (#{container_field_url})" end require "net/http" # Requesting the container URL with no cookie set will respond with a # redirect and a session cookie = ::Net::HTTP.get_response(url) unless = ["Set-Cookie"] raise FmRest::ContainerFieldError, "Container field's initial request didn't return a session cookie, the URL may be stale (try downloading it again immediately after retrieving the record)" end # Now request the URL again with the proper session cookie using # OpenURI, which wraps the response in an IO object which also responds # to #content_type url.open("Cookie" => ) end |
#upload_container_data(connection, container_path, filename_or_io, options = {}) ⇒ Object
Handles the core logic of uploading a file into a container field
59 60 61 62 63 64 65 66 67 68 69 70 |
# File 'lib/fmrest/v1/container_fields.rb', line 59 def upload_container_data(connection, container_path, filename_or_io, = {}) content_type = [:content_type] || DEFAULT_UPLOAD_CONTENT_TYPE connection.post do |request| request.url container_path request.headers['Content-Type'] = ::Faraday::Request::Multipart.mime_type filename = [:filename] || filename_or_io.try(:original_filename) request.body = { upload: Faraday::UploadIO.new(filename_or_io, content_type, filename) } end end |