user2158382
user2158382

Reputation: 4510

.JS.ERB can't recognize variables

I am new to .js.erb files, and I am using them because I need to construct a Javascript string that needs Ruby variables.

Here is my code.

pusher.js.erb

var pusher = new Pusher(PUSHER KEY);
var myChannel = pusher.subscribe('job_channel');
$(document).ready(function() {
    myChannel.bind('job_added', function(data) {
        addJob(data)
    });

    function addJob(data) {
        <% job = JSON.parse(data) %>
        var new_job = "HELLO <%= job.id %>";
        $('.job_list').append(new_job)
    };

});

data holds a Ruby object called job that I converted to JSON. I want to turn that JSON object back into a Ruby object and use its attributes to construct a Javascript string. I know I can simply just use data["id"] in this example, but this is just sample code and I need a lot more complicated Ruby stuff to go into that string.

When I try to start the server and load a page, I am getting this error:

undefined local variable or method `data' for #<#:0x007ffe07cb7e58> (in /PATH/javascripts/pusher.js.erb)

app/assets/javascripts/pusher.js.erb:17:in `block in singletonclass'
app/assets/javascripts/pusher.js.erb:65530:in `instance_eval'
app/assets/javascripts/pusher.js.erb:65530:in `singletonclass'
app/assets/javascripts/pusher.js.erb:65528:in `__tilt_70364478302900'
app/views/layouts/application.html.erb:21:in `_app_views_layouts_application_html_erb___1231815935649534974_70364476328360'

Upvotes: 0

Views: 906

Answers (1)

Puhlze
Puhlze

Reputation: 2614

ERB passes through text and performs operations or writes out text based on ruby code it sees inside certain escape sequences. You have two escape sequences that ERB will process:

<% job = JSON.parse(data) %>
var new_job = "HELLO <%= job.id %>";

data is not being defined in ERB / ruby scope, which is why you are seeing the above error. It appears you may be getting the ERB / ruby code mixed up with the javascript code. They operate independently of one another.

Upvotes: 1

Related Questions