Can I have a ruby code inside a .js file?

Hi all,

Can I have a ruby code inside a java script function written in .js file?

When I tried it, i got an error.

e.g. consider following function inside myscript.js file


function sayHi



alert(‘HI <%=name%>’);


But this works if I have above function in a rhtml file inside tag.

Any inputs in this regard will be really helpful.

Thanks and Regards,


no, you cannot have ruby code inside a standalone js file, as it is
your browser that requests the file directly from the webserver. it
is NOT being parsed/interpreted/executed on the server.

when you put the ruby code into the rhtml template within <script>
tags then that code IS being parsed as part of the template file.


Yes and no. You can't have Ruby code within a .js file stored in the public directory, but you could generate a javascript file from a controller (this will require some disabling any layouts, etc.). Your HTML will probably need to reference the generated javascript "file" directly, rather than through Rails' helper function.


Best regards

Peter De Berdt