Rails 3: Passing a string from Ruby to Javascript?
The Jist:
In a <script type="text/javascript">
I want to access a static (won't ever change after Rails delivers page to client) string from Ruby to Javascript.
More Detail (AKA: Why I want to do it.)
I use a push server called Juggernaut and it has to connect to the appropriate "channel", determined by a variable in the controller. The Juggernaut syntax for "listen开发者_如何学编程ing" to the Juggernaut server is:
j.subscribe("channel", function(data) { })
I want it to be:
j.subscribe(<%= @myChannel %>, function(data) { })
Most likely your @myChannel
doesn't contain ".
You should use:
j.subscribe("<%= @myChannel %>", function(data) { })
A different idea is to not embed your ruby code in your .js files but rather in the view itself.
So in your view, either set a javascript variable channel
or add "channel" as an attribute of some html element, whichever is more natural for your case. Then in your application javascript you can access that variable once the document is ready.
This has the side benefit that if / when channel changes the client doesn't need to re-download your javascript but can instead keep using it from cache, and that rails doesn't need to render the .js every time.
精彩评论