Skip to content

Instantly share code, notes, and snippets.

@iarie
Last active July 19, 2017 09:47
Show Gist options
  • Save iarie/f9f91648e534433af215bec8abe9bfa2 to your computer and use it in GitHub Desktop.
Save iarie/f9f91648e534433af215bec8abe9bfa2 to your computer and use it in GitHub Desktop.
RoR: catch send_file via cookies
<!-- Using ladda-button plugin and bootsrtap -->
<!-- setting data-attributes to link with unique token -->
<%= link_to download_products_event_path(event, format: :xlsx), class: "download-file-btn",
data: { token_value: SecureRandom.hex, token_name: "products_download_token_#{event.id}"} do %>
<button class="btn btn-outline btn-primary dim ladda-button" type="button" data-style="zoom-out">
<i class="fa fa-file-excel-o"></i> Download
</button>
<% end %>
<!-- @TODO: we could also check if token exists to disable button
in case of someone somehow will try to download same large file in different tabs -->
// Jquery + js-cookie (https://github.com/js-cookie/js-cookie)
$(document).ready(function () {
$('.download-file-btn').on('click', function(e){
e.preventDefault();
// updating GET action with token attributes provided
var token_name = $(this).data('token-name');
var token_value = $(this).data('token-value');
window.location.href = $(this).attr("href") + '?token_name=' + token_name + '&token_value=' + token_value
fileDownloadCheckTimer = window.setInterval(function () {
var cookie_value = Cookies.get(token_name)
if(cookie_value == token_value){
Cookies.remove(token_name) // reset cookies
Ladda.stopAll(); // reset button
clearInterval(fileDownloadCheckTimer);
};
}, 1000);
});
});
class EventsController < ApplicationController
### Action example using render axlsx
def download_products
token_name = params[:token_name]
token_value = params[:token_value]
respond_to do |format|
format.xlsx {
# setting cookies when download finishes
cookies[token_name] = {
value: token_value,
expires: 5.minutes.since,
}
render xlsx: "filename",
template: 'templates/xlsx/products.xlsx.axlsx',
locals: { products: resource.visible_products }
}
end
end
private
def resource
@_resource ||= Event.find(params[:id])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment