Skip to content
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 17 additions & 6 deletions lib/tus/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,20 +21,20 @@ def initialize(server_url)
@capabilities = capabilities
end

def upload(file_path)
def upload(file_path, metadata = nil)
raise 'No such file!' unless File.file?(file_path)

file_name = File.basename(file_path)
file_size = File.size(file_path)
io = File.open(file_path, 'rb')

upload_by_io(file_name: file_name, file_size: file_size, io: io)
upload_by_io(file_name: file_name, file_size: file_size, io: io, , metadata: metadata)
end

def upload_by_io(file_name:, file_size:, io:)
def upload_by_io(file_name:, file_size:, io:, metadata:)
raise 'Cannot upload a stream of unknown size!' unless file_size

uri = create_remote(file_name, file_size)
uri = create_remote(file_name, file_size, metadata)
# we use only parameters that are known to the server
offset, length = upload_parameters(uri)

Expand Down Expand Up @@ -71,16 +71,27 @@ def capabilities
response['Tus-Extension']&.split(',')
end

def create_remote(file_name, file_size)
def create_remote(file_name, file_size, metadata)
unless @capabilities.include?('creation')
raise 'New file uploading is not supported!'
end

if metadata.nil? then
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't use trailing then unless you are writing a one-liner.
The most common way to write such statements is metadata ||= {}

metadata = {}
end

metadata[:filename] = file_name

pairs = []
metadata.each do |key, value|
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is easier to use a brace-delimited block and place this code right at the request construction. Thus you will not need pairs (which is also a bad name choice too)

pairs << "#{key} #{Base64.strict_encode64(value)}"
end

request = Net::HTTP::Post.new(@server_uri.request_uri)
request['Content-Length'] = 0
request['Upload-Length'] = file_size
request['Tus-Resumable'] = TUS_VERSION
request['Upload-Metadata'] = "filename: #{Base64.strict_encode64(file_name)},is_confidential"
request['Upload-Metadata'] = pairs.join(',')

response = nil

Expand Down