1

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 "listening" to the Juggernaut server is:

j.subscribe("channel", function(data) { }) 

I want it to be:

j.subscribe(<%= @myChannel %>, function(data) { }) 
2
  • 1
    Your idea is a fine one. What is your question? How is it not working?
    – Larry K
    CommentedSep 22, 2011 at 1:56
  • If I try alert(<%= @myChannel %>) everything after that line does not work, and the alert doesn't execute. Furthermore, if I put that Ruby code in as a parameter of juggernaut, the juggernaut subscribe function doesn't execute.
    – Derek
    CommentedSep 22, 2011 at 2:03

2 Answers 2

4

Most likely your @myChannel doesn't contain ".

You should use:

j.subscribe("<%= @myChannel %>", function(data) { }) 
1
  • Ah, perfect! A simple beginners mistake!
    – Derek
    CommentedSep 22, 2011 at 3:30
2

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.

2
  • Great suggestion. Never thought of that. Thanks!
    – Derek
    CommentedSep 22, 2011 at 3:30
  • +1 Yes, this is the best way. It also enables you to use the tool chain to properly handle the js file: minimized and concatenated with other js so that only one js is downloaded per html page. A third option is to have your html page explicitly initiate the js actions by calling a start js method. Then pass the channel as a parameter to the call.
    – Larry K
    CommentedSep 22, 2011 at 14:07

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.