Or do both! In this example, this much abstraction is silly, but as soon as this JS starts doing anything even slightly complex, this will be the best way. Pass more data, less code, via generated js responses. Real complex js logic should always be included statically on the page.

Lastly, I might also argue the true "best" way is only render JSON from the server, and you have statically included JS that handles fetching that via AJAX, and handling what to do with the page based on that data. This way you never "generate" executable javascript server side at all, which is very clean.

+1 to this. Generating complex chunks of source code is almost never a good idea. If you're reusing a nontrivial chunk of JS, it should be a function in your JS files.
–
millimooseDec 5 '12 at 22:29

In your second piece of code, you have two nested 's, when one should be a ".
–
XymostechDec 5 '12 at 22:32

The message in the javascript respond block is just a short one line message so would that be ok to put js in the ruby controller action?
–
perseveranceDec 5 '12 at 22:50

@persistence It'll work that way, sure. It depends on how clean you want it to be, and how complex the real logic is. (Your example isn't real logic). Anything beyond a single function being called with an argument or two, should be refactored out for sure. But in an ideal world, you would never have JS in your ruby. How ideal do you want to be?
–
Alex WayneDec 5 '12 at 22:54