Samstag, Juni 28, 2008

Render a simple Javascript with Rails

Though its a simple task there is no well documented solution. Most I googled did not work. I just needed to write a large javascript array dynamicly. If you just do a render :text => js your resulting content type will be text/html which was a problem for the IE. But setting the mime_type like

render :text => js,:mime_type => Mime::Type.lookup("application/javascript")

does not do the trick. What you have to do is setting the content type in the headers variable:

headers["Content-Type"] = "text/javascript".

I got the best results when I also added a .js to the route so you can call it like a static javascriptfile. If you want to do more complicated things you may check out the minus_r plugin of Dan Webb:

1 Kommentar:

Unknown hat gesagt…

Thanks! Just what I needed.