Skip to content

Instantly share code, notes, and snippets.

@suzumura-ss
Last active December 11, 2015 07:16
Show Gist options
  • Save suzumura-ss/e58ee0e4e3b18f062e46 to your computer and use it in GitHub Desktop.
Save suzumura-ss/e58ee0e4e3b18f062e46 to your computer and use it in GitHub Desktop.
fileUploader example with ruby-grape
#!/usr/bin/env rackup
# encoding: UTF-8
=begin
# start application
$ mkdir files
$ ./fileUploader.ru
# upload
$ curl localhost:9292/files -F comment="hello,world" -F "body=@example.txt;type=image/jpg"
#=> Content-Type: application/json
{"id":"d20f7400-81f6-0133-570b-7831c1cfdb38"}
# download body
$ curl localhost:9292/files/d20f7400-81f6-0133-570b-7831c1cfdb38
#=> Content-Type: image/jpg
(bytes)
# download comment
$ curl localhost:9292/files/d20f7400-81f6-0133-570b-7831c1cfdb38/comment
#=> Content-Type: text/plain
hello,world
# delete content
$ curl localhost:9292/files/d20f7400-81f6-0133-570b-7831c1cfdb38 -X DELETE
{"state":"deleted"}
=end
require 'grape'
require 'uuid'
require 'yaml/store'
require 'pp'
module FileStore
class << self
@@me = nil
def me
unless @@me
filename = 'files/contents.yaml'
File.write(filename, {files:{}}.to_yaml) unless File.exist?(filename)
@@me = YAML::Store.new(filename)
end
@@me
end
def find(id)
me.transaction do
me[:files][id]
end
end
def store(body, comment)
id = UUID.generate
File.write("files/#{id}", body.tempfile.read)
me.transaction do
me[:files][id] = {comment:comment, name:body.filename, type:body.type}
end
id
end
def destroy(id)
me.transaction do
if me[:files].delete(id)
File.unlink("files/#{id}")
true
else
false
end
end
end
end
end
class FileStreamer
def initialize(file_path)
@file_path = file_path
end
def each(&blk)
File.open(@file_path, 'rb') do |file|
file.each(10, &blk)
end
end
end
class FileUploader < Grape::API
content_type :txt, 'text/plain'
content_type :json, 'application/json'
format :json
default_format :json
resource :files do
params do
requires :comment, type: String
requires :body, type: File
end
post '' do
id = FileStore.store(params.body, params.comment)
status 201
{id:id}
end
params do
requires :id, type: String
end
get ':id' do
obj = FileStore.find(params[:id])
unless obj
status 404
return {error: '404 not found.'}
end
status 200
content_type obj[:type]
file FileStreamer.new("files/#{params.id}")
end
params do
requires :id, type: String
end
get ':id/comment' do
obj = FileStore.find(params[:id])
unless obj
status 404
return {error: '404 not found.'}
end
status 200
content_type 'text/plain'
body obj[:comment]
end
params do
requires :id, type: String
end
delete ':id' do
if FileStore.destroy(params.id)
status 200
return {state:'deleted'}
else
status 404
return {error: '404 not found.'}
end
end
end
end
run FileUploader
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment