title: drying up rails controller code for data export
body: <p>Not sure if this is an appropriate question so forgive me. </p>
  
  <p>I have the following code in a controller action</p>
  
  <pre><code>unless @users.empty?
    book = Spreadsheet::Workbook.new
    sheet1 = book.create_worksheet :name =&gt; 'export'
    sheet1.row(0).concat ["Label1", "Label2", "Label3"]
    @users.each_with_index do |e, i|
      sheet1.row(i+1).concat([e.field1, e.field2, e.field3])
    end
    require 'stringio'
    data = StringIO.new ''
    book.write data
    send_data data.string, :type=&gt;"application/excel", :disposition=&gt;'attachment', :filename =&gt; "export_#{l(Date.today)}.xls"
  end
  </code></pre>
  
  <p>This allows me to have a button on a form that runs an export. Whilst this is very useful, I am using this code all over the place. In fact, I have 19 instances of this code across various controllers in the app. Is there a way I can move this code to another file, and pass into it a hash of the labels and fields so that I only have to maintain one instance of the export code?</p>
  
  <p>thanks</p>