1

I'm creating my own version of Rayan Bates CSV screencast here...

http://railscasts.com/episodes/396-importing-csv-and-excel

I have this in my model...

 def self.open_spreadsheet(file)
    case File.extname(file.original_filename)
    when ".csv" then Csv.new(file.path, nil, :ignore)
    when ".xls" then Excel.new(file.path, nil, :ignore)
    when ".xlsx" then Excelx.new(file.path, nil, :ignore)
    else raise "Unknown file type: #{file.original_filename}"
    end
  end

...and am getting this error in my app...

 NameError in StudentsController#import

uninitialized constant Student::Csv

Rails.root: /home/wintas/railsApps/t4
Application Trace | Framework Trace | Full Trace

app/models/student.rb:25:in `open_spreadsheet'
app/models/student.rb:13:in `import'
app/controllers/students_controller.rb:12:in `import'

I can't find where the class 'Csv' is initialized, or where it should be coming from. Any help appreciated.

skaffman
  • 398,947
  • 96
  • 818
  • 769
Mark Locklear
  • 5,044
  • 1
  • 51
  • 81

4 Answers4

2

I believe that since that Railscast was published, Roo has been updated to namespace Csv, Excel, and Excelx under the Roo namespace. Try this instead:

def self.open_spreadsheet(file)
  case File.extname(file.original_filename)
  when ".csv" then Roo::Csv.new(file.path, nil, :ignore)
  when ".xls" then Roo::Excel.new(file.path, nil, :ignore)
  when ".xlsx" then Roo::Excelx.new(file.path, nil, :ignore)
  else raise "Unknown file type: #{file.original_filename}"
  end
end
Dylan Markow
  • 123,080
  • 26
  • 284
  • 201
2

Newer equivalent of that function using roo 1.13.2 is:

def self.open_spreadsheet(file)
  case File.extname(file.original_filename)
    when ".csv" then Roo::CSV.new(file.path, file_warning: :ignore)
    when ".xls" then Roo::Excel.new(file.path, file_warning: :ignore)
    when ".xlsx" then Roo::Excelx.new(file.path, file_warning: :ignore)
    else raise "Unknown file type: #{file.original_filename}"
  end
end
jesal
  • 7,852
  • 6
  • 50
  • 56
0

In the ruby standard library, csv is all caps: CSV. Does that help?

Peter P.
  • 3,221
  • 2
  • 25
  • 31
  • `Csv` is a class within the `Roo` gem, different from Ruby's stdlib `CSV` class. – Dylan Markow Feb 28 '14 at 01:19
  • Yes I realize, but in the Railscast tutorial, it appears, Ryan Bates is using the ruby CSV library to start with, so I thought this might be a source of confusion for the OP. In anycase, you're probably right, its probably a gem version issue necessitating namespacing – Peter P. Feb 28 '14 at 02:05
  • 1
    Turns out @PeterP was correct about the capitalization but not for the correct reason. See jesai's answer as that is what fixed it for me. – aarona May 05 '15 at 23:40
0

try restarting the server; I had the problem before and restarting the server resolved the issue