I am using Handlebar in my Rails 3.2 jquery mobile application.
I am trying to write a switch case statement inside a Coffeescript method like
Handlebars.registerHelper 'status', (blog) ->
switch(parseInt(blog.status))
when [0..20]
status = "active"
when [20..40]
status = "Moderately Active"
when [40..60]
status = "Very Active"
when [60..100]
status = "Hyper Active"
return status
I am not getting any result . How to use range in when . Please suggest
Your
switchwon’t work as Cygal notes in the comments (i.e. see issue 1383). Aswitchis just a glorifiedif(a == b)construct and you need to be able to say things like:and have it work when you
switchon an array. The CoffeeScript designers thought adding a (fragile) special case to handle arrays (which is all[a..b]is) specially wasn’t worth it.You can do it with an
if:Or with short circuiting
returns like this:Note that you have three special cases that you need to add strings for:
status < 0.status > 100.statusisNaN. This case would usually fall under the final “it isn’t less than or equal to 100” branch sinceNaN => nandNaN <= nare both false for alln.Yes, you’re absolutely certain that the status will always fall within the assumed range. On the other hand, the impossible happens all the time software (hence the comp.risks mailing list) and there’s no good reason to leave holes that are so easily filled.
Also note the addition of the radix argument to the
parseIntcall, you wouldn’t want a leading zero to make a mess of things. Yes, the radix argument is optional but it really shouldn’t be and your fingers should automatically add the, 10to everyparseIntcall you make.