Skip to content

Instantly share code, notes, and snippets.

@dimitertodorov
Last active November 11, 2016 01:44
Show Gist options
  • Save dimitertodorov/3e7f30235ec80d0afa4879fd9cc74aaf to your computer and use it in GitHub Desktop.
Save dimitertodorov/3e7f30235ec80d0afa4879fd9cc74aaf to your computer and use it in GitHub Desktop.
Grape Attachment Route
params do
requires :id, type: String
requires :work_log_id, type: String
requires :attachment_field, type: String
end
get ":id/work_log/:work_log_id/:attachment_field" do
find_elixir_object
authorize! permission_key(:read, @elixir_object), @elixir_object
error!({ error: "No Work Log Entry for \#{params[:id]} with ID \#{params[:work_log_id]}"}, 404) if @elixir_object.work_log_entries.blank?
key = @elixir_object.work_log_entries.first.class.elixir_primary_key
work_log_entry = @elixir_object.work_log_entries.select{|w| w[key.to_sym]==params[:work_log_id]}
if work_log_entry.blank?
error!({ error: "No Work Log Entry for \#{params[:id]} with ID \#{params[:work_log_id]}"}, 404)
else
content_type "application/octet-stream"
env['api.format'] = :binary
attachment = work_log_entry.first[params[:attachment_field].to_sym]
error!({ error: "No Work Log Attachment \#{params[:attachment_field]} for \#{params[:work_log_id]} on \#{params[:id]}"}, 404) unless attachment
filename = File.split(attachment.name).last
header['Content-Disposition'] = "attachment; filename=\#{filename}"
## This calls getEntryBlob(String formName, String entryID, int fieldID, String filePath)
work_log_entry.first.get_blob(params[:attachment_field].to_sym, Rails.root.join("tmp/\#{filename}").to_s)
## Would prefer to call getEntryBlob(String formName, String entryID, int fieldID) and return the bytes directly.
File.binread(Rails.root.join("tmp/\#{filename}"))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment