Where should I place code which generates Excel spreadsheet?
-
12-09-2019 - |
Question
I am using spreadsheet gem to generate native Excel file. This is not CSV, XML file. Ordinary Ruby code is used to create the file. The generated Excel file (kept in StringIO
) is forwarded to a client using send_data
method. I need send_data
method because of its parameters like disposition
.
The data for the Excel is retrieved in controller method just like for ordinary HTML, JS requests. However I placed the code to generate the spreadsheet in controller protected method. Not in a view as I should.
Is there an elegant solution to above problem compliant with MVC design pattern?
Update: There is no popular and accepted by all solution to above problem but at least I know all possible ideas.
Solution
- Create an excel library in your lib folder in which you include your xls generation routine as well as a method that overrides ActionController's
render
method. - In a model that should be rendered as xls implement a method called
to_excel
method which generates a hash that you can provide to your xls routine. Doing it this way, you'll get something really "Railsy". In your controller you'll just call
render :xls => @model
OTHER TIPS
The lib directory is meant as a place for code that isn't strictly part of the MVC structure, but will be needed by multiple models, views, or controllers. It can be brought in with a require
when needed.
However, if you only need the code in a single controller, you'd be just as well off putting it into that controller's helper. That way it's auto-loaded and at your fingertips. Plus, it makes sense: it's code to help a specific controller.
Either way, don't leave it in your controller or try to wedge it into your view.
i just did this today for my app hope this helps for an excel o/p ; never used any plugin
controller: def export pr = Program.find(session[:pr_id]) headers['Content-Type']="application/vnd.ms-excel" headers['Content-Dispositon']='attachment;filename="report.xls"' @voucherdatas = Voucherdata.find_all_by_pr_name(pr.pr_name) end
view: export.html.erb
manager "reports/voucherdatas", :object =>@voucherdatas %>routes.rb map.resources :reports ,:collection =>{:export =>:get}
whereever u want the link give
link_to "Export As Excel", export_reports_url, :popup=>true