Skip to content

Instantly share code, notes, and snippets.

@jaymcgavren
Created February 6, 2026 00:16
Show Gist options
  • Select an option

  • Save jaymcgavren/c8f5824bf1dc90aad0c5e12f58ea9179 to your computer and use it in GitHub Desktop.

Select an option

Save jaymcgavren/c8f5824bf1dc90aad0c5e12f58ea9179 to your computer and use it in GitHub Desktop.
A Ruby script that accepts multiple files as command line arguments. It outputs an array of JSON objects, one for each input file. The result can be embedded in an all-in-one .html file.
#!/usr/bin/env ruby
require 'json'
require 'base64'
require 'pathname'
# require 'mime/types'
# Perplexity.ai prompt:
# Write a Ruby script that accepts multiple files as command line arguments. It
# should output an array of JSON objects, one for each input file, with these
# attributes:
# - 'name': the name of the file.
# - 'mime': the MIME type of the file.
# - 'data': the file contents, encoded in base64.
# If no files provided, show usage and exit
if ARGV.empty?
STDERR.puts "Usage: ruby script.rb file1 [file2 ... fileN]"
exit 1
end
def mime_type_for(path)
# Use MIME::Types if available, fall back to file command-like heuristic
if defined?(Mime::Types)
mime = MIME::Types.type_for(path).first
return mime.to_s if mime
end
# Fallback: simple extension-based (not perfect, but better than nothing)
ext = File.extname(path).downcase
case ext
when ".txt" then "text/plain"
when ".json" then "application/json"
when ".csv" then "text/csv"
when ".jpg", ".jpeg" then "image/jpeg"
when ".png" then "image/png"
when ".gif" then "image/gif"
when ".svg" then "image/svg+xml"
when ".pdf" then "application/pdf"
when ".webp" then "image/webp"
when ".wav" then "audio/wav"
when ".mp3" then "audio/mpeg"
else "application/octet-stream"
end
end
results = ARGV.map do |file_path|
begin
unless File.exist?(file_path)
raise Errno::ENOENT
end
data = File.binread(file_path)
encoded = Base64.strict_encode64(data)
{
'name' => File.basename(file_path),
'mime' => mime_type_for(file_path),
'data' => encoded
}
rescue => e
{
'name' => File.basename(file_path),
'mime' => 'application/octet-stream',
'data' => Base64.strict_encode64("Error: #{e.message}")
}
end
end
puts JSON.pretty_generate(results)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment