Basically I have a respond_to block in my controller action:
respond_to do |format|
format.js { render :js => "$('#test').html('<div class='colorize'>Test</div>');" }
end
I am also trying to add a css class colorize to the div block that will be rendered via js but using quotes there breaks the code. How do I get this working with the class added in?
Save yourself a gigantic headache here, and don’t put anything besides the simplest JS in your ruby handlers.
And then on the page or via included script, declare a function:
Don’t put JS in your Ruby.
Or you could use a real view template:
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.
See how now you dont have any JS in your ruby at all? Or any ruby in your JS for that matter? Just sending data between server and client. Man that’s nice. Just how I like it.