Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SyntaxError using Case Expression on Sinatra 1.2.0 and Ruby 1.9.2

I'm using Sinatra 1.2.0 with Ruby 1.9.2 (I need to work with this version of Ruby for this project) and I don't know why I keep getting this SyntaxError. I can reproduce this error when using the following in my index.erb:

<% @status = "foo" %>
The case is: <br />

<% case @status %>
  <% when "foo" %>
    It's a FOO!
  <% when "bar" %>
    It's a BAR!
  <% else %>
    It's something else...!
<% end %>

Error:

SyntaxError at /
/Users/foo/Workspace/sinatra_case_test/views/index.erb:4: syntax error, unexpected tIVAR, expecting keyword_when ; case @status ; @_out_buf.concat "\n " ^ 
/Users/foo/Workspace/sinatra_case_test/views/index.erb:5: syntax error, unexpected keyword_when, expecting keyword_end ; when "foo" ; @_out_buf.concat "\n It's a FOO!\n " ^ 
/Users/foo/Workspace/sinatra_case_test/views/index.erb:7: syntax error, unexpected keyword_when, expecting keyword_end ; when "bar" ; @_out_buf.concat "\n It's a BAR!\n " ^ 
/Users/foo/Workspace/sinatra_case_test/views/index.erb:13: syntax error, unexpected keyword_ensure, expecting $end

Funny thing: The mentioned line 13 doesn't actually exist in index.erb.

You can check the details of the app on Github. It basically consists of the index.erb mentioned above.

Thanks a lot for your kind help!

like image 335
Javier Avatar asked Oct 27 '25 16:10

Javier


1 Answers

The problem is that you can't have arbitrary statements in a case statement. This is actually a very rare case where ruby limits where you can have code.

The way ERb works is that it inserts statements around your code to which it channels the output. You can see it in your error log. In this case the code that is generated is something like this:

case @status
@_out_buf.concat "\n "
when "foo"
@_out_buf.concat "\n It's a FOO!\n "
when "bar"
@_out_buf.concat "\n It's a BAR!\n "
else
@_out_buf.concat "\n It's something else...!\n "
end

As you see the second line here is what causes the problem. You might be able to solve it is have your ERb suppress the newline concat:

<% case @status; when "foo" %>

or (though this might not work):

 <% case @status -%>
   <% when "foo" %>
like image 103
Jakub Hampl Avatar answered Oct 30 '25 07:10

Jakub Hampl