I am trying out CoffeeScript in my Rails 3.1 app. However, I am not able
to figure out how to break long lines in CoffeeScript without getting the
above error
For example, how/where would you break the following line of code
alert x for x in [1,2,3,4,5] when x > 2
if you wanted something like
alert x for
x in [1,2,3,4,5]
when x > 2
In my vimrc, I have set
ts=2, sw=2 and I expand tabs.
And yet, I cannot get something as simple as the line above to work properly.
My Gemfile.lock shows coffee-script-2.2.0 with coffee-script-source 1.1.3
If you have a comprehension that is too long you can break it with \
as @brandizzi mentions, but I think you might have better luck just using comprehensions where they make sense and expanding to 'regular' code where they don't:
alert x for x in [1,2,3,4,5] when x > 2
...can be rewritten as...
for x in [1,2,3,4,5]
alert x if x > 2
...or even...
for x in [1,2,3,4,5]
if x > 2
alert x
In other words, comprehensions are syntactic sugar for short, concise snippets - you don't have to use them for everything.
You're trying to spread a comprehension out over multiple lines, which isn't allowed. It either needs to be on one line, or be a proper loop. Your one line version works as expected, so I'll show the loop version:
for x in [1..5] when x > 2
alert x
You may find it helpful to toss small things like this into the CoffeeScript compiler at http://jashkenas.github.com/coffee-script/ to see if they're compiling to what you'd expect.
I do not understand the inner details of CoffeeScript syntax, so I cannot say what is going wrong in detail. The error is a bit clear, however: you cannot put a newline between the for
and its iterator variable. Also, you did not get this error yet, but you cannot put a newline between the iterated object and the when
clause. However, if you really want to do it, it is easy: put backslashes at the end of the first and second lines.
console.log x for \
x in [1,2,3,4,5] \
when x > 2