Topic: Strange problem with session variables

Hi!

I've written a controller method to export data to an excel worksheet.  The column headings for the worksheet are stored in a session variable called :people_columns.  If I simply create a new excel spreadsheet, close it, and send it back to the browser, it works fine:

def export
  workbook = Spreadsheet::Excel.new "#{RAILS_ROOT}/public/spreadsheets/test.xls"
  worksheet = workbook.add_worksheet "People"
  workbook.close
  send_file "#{RAILS_ROOT}/public/spreadsheets/test.xls", :stream => false, :disposition => 'attachment'
end

However, if I iterate over my session variable...
def export
  workbook = Spreadsheet::Excel.new "#{RAILS_ROOT}/public/spreadsheets/test.xls"
  worksheet = workbook.add_worksheet "People"
 
  current_column = 0
  for column_name in session[:people_columns]
    worksheet.write(0, current_column, column_name)
    current_column += 1
  end
   
  workbook.close
  send_file "#{RAILS_ROOT}/public/spreadsheets/test.xls", :stream => false, :disposition => 'attachment'
end

It works fine as far as generating the spreadsheet and sending it to the browser, but it replaces each element of my session[:people_columns] array with "".  I've found this by using debug() in a view after the export method has been called.  Also, the export method is called by a link_to tag in the view.

Any ideas as to what is causing this strange behavior?

Last edited by MadPhoenix (2006-11-09 01:58:40)

Re: Strange problem with session variables

You may want to try duplicating the column_name string before sending it out. Perhaps it is getting replaced with an empty string somewhere in that write method:

worksheet.write(0, current_column, column_name.dup)

Also, you can use the index of the array instead of keeping track of the current column separately:

session[:people_columns].each_with_index do |column_name, column_index|
  worksheet.write(0, column_index, column_name.dup)
end

Railscasts - Free Ruby on Rails Screencasts

Re: Strange problem with session variables

Good call, that worked!  Perhaps time to put a bug report in with the folks writing the spreadsheet::excel gem.