Skip to content

Instantly share code, notes, and snippets.

@marvindpunongbayan
Last active January 15, 2020 07:50
Show Gist options
  • Save marvindpunongbayan/51eee506e3d718f97677 to your computer and use it in GitHub Desktop.
Save marvindpunongbayan/51eee506e3d718f97677 to your computer and use it in GitHub Desktop.
# Controller Action
def custom_download
id = params[:id]
# model variable should have value like: Slide, DriveDocument, User, etc.
model = params[:model]
# file variable: should have paperclip object name like: attachment, image, etc.
file = params[:file]
if model.present? && id.present? && file.present?
begin
object = Object.const_get(model).find_by(id: id)
data = object.send(file)
data_content_type = object.send("#{file}_content_type")
rescue => e
Rollbar.error(e)
end
if object.present? && data_content_type.present? && data.present? && data.exists?
if Rails.env.development?
send_file data.path, filename: data.original_filename and return
else
data_read = open(data.expiring_url)
send_data data_read.read, filename: data.original_filename, type: data_content_type, disposition: 'attachment' and return
end
else
redirect_to root_path, alert: "We cannot find the file, please try again later." and return
end
else
redirect_to root_path, alert: "Invalid parameters, please try again later." and return
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment