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

**URL:** <https://discuss.rubyonrails.org/t/can-i-have-a-ruby-code-inside-a-js-file/6601>\
**Category:** rubyonrails-talk\
**Created:** [January 2, 2007, 3:26pm UTC](https://discuss.rubyonrails.org/t/can-i-have-a-ruby-code-inside-a-js-file/6601 "2007-01-02T15:26:44Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![Medha\_Kulkarni](https://avatars.discourse-cdn.com/v4/letter/m/e5b9ba/32.png) [@Medha\_Kulkarni](https://discuss.rubyonrails.org/u/Medha_Kulkarni)\
**Post date:** [January 2, 2007, 3:26pm UTC](https://discuss.rubyonrails.org/t/can-i-have-a-ruby-code-inside-a-js-file/6601/1 "2007-01-02T15:26:44Z")

</div>

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

myscript.js

function sayHi

{

\<%name=“xyz”%\>;

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,

Medha.

---

<div class="post-metadata">

**Author:** ![Chris\_Hall](https://avatars.discourse-cdn.com/v4/letter/c/0ea827/32.png) [@Chris\_Hall](https://discuss.rubyonrails.org/u/Chris_Hall)\
**Post date:** [January 2, 2007, 3:52pm UTC](https://discuss.rubyonrails.org/t/can-i-have-a-ruby-code-inside-a-js-file/6601/2 "2007-01-02T15:52:30Z")

</div>

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.

Chris

---

<div class="post-metadata">

**Author:** ![Faisal\_N\_Jawdat](https://avatars.discourse-cdn.com/v4/letter/f/34f0e0/32.png) [@Faisal\_N\_Jawdat](https://discuss.rubyonrails.org/u/Faisal_N_Jawdat)\
**Post date:** [January 2, 2007, 5:06pm UTC](https://discuss.rubyonrails.org/t/can-i-have-a-ruby-code-inside-a-js-file/6601/3 "2007-01-02T17:06:45Z")

</div>

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.

-faisal

---

<div class="post-metadata">

**Author:** ![Peter\_De\_Berdt](https://avatars.discourse-cdn.com/v4/letter/p/53a042/32.png) [@Peter\_De\_Berdt](https://discuss.rubyonrails.org/u/Peter_De_Berdt)\
**Post date:** [January 2, 2007, 11:53pm UTC](https://discuss.rubyonrails.org/t/can-i-have-a-ruby-code-inside-a-js-file/6601/4 "2007-01-02T23:53:35Z")

</div>

[http://www.danwebb.net/2006/11/24/minusmor-released](http://www.danwebb.net/2006/11/24/minusmor-released)

Best regards

Peter De Berdt
