send_file, send_data の include
Spree::Api
に自作Apiを追加するとき、send_file が NoMethodError でしたので include する方法を調べました。
app/controllers/spree/api/your_extension_controller.rb module Spree module Api class YourExtensionController < Spree::Api::BaseController # for send_file include ActionController::DataStreaming def download # authorize with administrator token as get paramater if it need authorize! :download, Spree::YourExtension, params[:token] file_path = "path/to/sample/file.csv" respond_to do |format| format.html { redirect_to :action => "download", :format => "csv"} format.csv { send_file file_path, :filename => File.basename(file_path) , type: "application/csv" } end end end end end
routing はこのような感じで。
your_extension_root/config/routes.rb Spree::Core::Engine.routes.draw do # for your_extension routing get 'api/download_your_extension/:id', controller: 'api/your_extension', action: 'download', defaults: { format: 'csv' }, as: :api_your_extension end
http://YOURDOMAIN.com/api/download_your_extension/file.csv?token=YOUR_API_TOKEN
または
http://YOURDOMAIN.com/api/download_your_extension/file?token=YOUR_API_TOKEN => redirect http://YOURDOMAIN.com/api/download_your_extension/file.csv?token=YOUR_API_TOKEN
でファイルをダウンロードできます。
YOUR_API_TOKEN は admin/users 画面上で管理者ユーザのアカウントで Generate してください。
tokenでの認証は、管理者自身がダウンロードするのであれば、都度ログインすれば不要なことですけどね。