AgostinoX
AgostinoX

Reputation: 7683

rails, erb in javascript: how to remove it

I have created a javascript in the tag of my application.erb.html.
That manages an asynchronous upload of a file (actually using plupload, but that's not relevant to the question).
The javascript code that initializes the uploader object is the following:

$(function() {

var uploader = new plupload.Uploader(
    {
        browse_button: 'plupload_browse',
        url: <%= upload_tmp_path(:format => :json) %>'
    });

//...

}

As you can see in the url line, since i am in a erb page, i rely on <%= %> tags in order to pass the script the upload url.
Now, for modularity reasons, i want to put this script in its ad-hoc .js file.
Since i can't use <%= %> tags anymore, what is my best option to pass such a script the piece of information required?

Upvotes: 1

Views: 217

Answers (2)

Richard Peck
Richard Peck

Reputation: 76784

DOM

The bottom line is you're going to have to pass the data to JS through your HTML

As JS is client-side, and Rails is server-side, the only way to pass data to an independent JS script (not directly rendered by Rails) is to use either something like gon, as suggested by apneadiving, or by setting the url in a data attribute in your HTML directly:

#app/controllers/application_controller.rb
before_action :set_gon

private

def set_gon
    gon.push({
       upload_tmp_path: upload_tmp_url(:format => :json)
    })
end

#app/views/layouts/application.html.erb
<%= include_gon %>

This will allow you to call the url in your JS as follows:

#app/assets/javascripts/application.js
gon.upload_tmp_path

Upvotes: 1

Brad Werth
Brad Werth

Reputation: 17647

Just add it as a custom data attribute on a predictable element on page, the element configured as the browse_button seems a likely candidate.

Upvotes: 2

Related Questions