6

I'm creating a Sinatra app that takes an uploaded CSV file and puts its contents in a hash. When I reference this hash in my app.rb like so:

hash = extract_values(path_to_filename)

I keep getting this error message:

undefined method `bytesize' for Hash:0x007fc5e28f2b90 #object_id

file: utils.rb location: bytesize line: 335

I read somewhere that this is a Webrick issue. I switched to Thin, the error's the same.

My hash / CSV file is of very small size, so it can't be the issue.

I'm using ruby 1.9.3p374.

Thanks!

fullstackplus
  • 1,061
  • 3
  • 17
  • 31
  • 1
    If I am not wrong, the bytesize method is only for string. Are you sure that you are passing the correct arg? – Thiago Lewin Jun 06 '13 at 16:52
  • 4
    If you could supply a bit more code, that would be very helpful. I'm guessing that `hash = …` is the last expression in a Sinatra route, but I'm guessing and that's the problem with this problem! – ian Jun 06 '13 at 18:54
  • You haven't given us nearly enough information and anything we say now is only speculation. We need a sample of the CSV, along with the code, that duplicates the problem before we can give you a reasonable answer. Based on experience I doubt Sinatra, Webrick, Thin or CSV are the problem, and instead it's most likely in `extract_values()`. As is, this is not a real question because it is vague and incomplete. – the Tin Man Jun 08 '13 at 22:31

2 Answers2

14

This looks like a duplicate of Undefined method `bytesize' for #<Hash>

Sinatra is expecting a string be returned (i.e. last line) of the route method; you can't just return a straight hash.

Community
  • 1
  • 1
Luke Antins
  • 2,010
  • 1
  • 19
  • 15
  • 1
    Thank you, that was indeed the problem. I didn't know that one must return a string in a Sinatra route. I tried to change this by return nil (never a good strategy) and iterating over the hash in the app.rb. Now I know that one must pass the collection to a view template, and iterate over it one the view. – fullstackplus Jun 09 '13 at 11:38
  • Glad you solved the problem, kudos on posting your solution too :) – Luke Antins Jun 09 '13 at 22:10
3

Solved:

1) pass the collection to the view:

get '/file/:filename' do
  filename = params[:filename]
  @rows = extract_values(testfile_path(filename))
  haml :search_term
end

2) iterate over it in the view template (erb / haml):

%ul
 - @rows.each do |hash|
  %li
   Id: #{hash[:id]}, Keyword: #{hash[:keyword]}, Searches: #{hash[:searches]}
fullstackplus
  • 1,061
  • 3
  • 17
  • 31