sivabudh
sivabudh

Reputation: 32635

Is it possible to do code generation in Coffeescript?

Say I have some Coffeescript (with Underscore.js mixed in) like this:

someData =
  hello: 'haha'
_(3).times (index) ->
  someData["key-#{index}"] = index

The value of someData will then be:

hello: 'haha'
key-0: 0
key-1: 1
key-2: 2

It would be nice if Coffeescript had some syntactic sugar that allows me to write something like this:

    someData =
      hello: 'haha'
<%
    _(3).times (index) ->
%>
      key-#{index}: index

which would produce someData whose value would be identical to the original.

Is there such facility in Coffeescript?

Upvotes: 0

Views: 505

Answers (3)

Blake Miller
Blake Miller

Reputation: 805

Short answer: Yes, sort of.

Slightly less short answer: You can do what the OP is after in fine style, since coffeescript is written in coffeescript (which is written in coffeescript ;). Sth like ERB templates are probably a better choice if your use-case is very simple, but there's nothing like programmatically manipulating AST structures for really powerful & reusable code-generation.

In this regard, Coffeescript shows something almost kinda-sorta halfway like http://en.wikipedia.org/wiki/Homoiconicity (the joy of lisps) but not really.

Here's an example: http://blog.davidpadbury.com/2010/12/09/making-macros-in-coffeescript/

nostalgic musing follows

"javascript" was inspired by http://en.wikipedia.org/wiki/Scheme_(programming_language) ... before it was called javascript ... and so coffeescript is kinda bringing JS back to its roots, eliding the marketing jibberish in its syntax, which was shoehorned in because of ill-conceived micromanagement on the part of Sun & Netscape executives.

Upvotes: 0

tokland
tokland

Reputation: 67860

To complement Trevor's answer: code generation (a'la Lisp) is indeed powerful, but you can also build structures with some basic abstractions. For your example (it uses a couple of functions from this underscore mixin):

data = _(
  hello: 'haha'
).merge(_([0..2]).mash (x) -> ["key-" + x, x])

Upvotes: 1

Trevor Burnham
Trevor Burnham

Reputation: 77416

Short answer: No.

Longer answer: This kind of syntax would go beyond CoffeeScript's intent of being a simple language that's ~1:1 with JavaScript. However, you could use another templating language on top of CoffeeScript. In fact, with Rails 3.1, it's pretty straightforward to have a .coffee.erb file where Ruby code can be used to generate CoffeeScript code, much like your hypothetical example.

Upvotes: 5

Related Questions