Sinatra: Undefined method bytesize for Hash [closed]
Asked Answered
K

2

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!

Kellsie answered 6/6, 2013 at 16:45 Comment(3)
If I am not wrong, the bytesize method is only for string. Are you sure that you are passing the correct arg?Matlick
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!Insecticide
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.Indicate
A
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.

Arbiter answered 8/6, 2013 at 23:58 Comment(2)
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.Kellsie
Glad you solved the problem, kudos on posting your solution too :)Arbiter
K
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]}
Kellsie answered 9/6, 2013 at 11:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.