Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have an external javascript plugin and there is a lot of code like this where the image src attribute is built dynamically.

$prod.append("<img class='fx_shadow' id='shd_" + i + "' + src='" + folderAssets + "/shadow_fx.png' />");

With rails 4.1+, I am precompiling the related images and assets that this external code provides and references above. Naturally, the images fail to load in production because using direct src attributes doesn't capture the fingerprint of the digested and precompiled image.

How do I call the asset_url method (which does output the correct asset file name with the digest) properly from an external javascript file rather than a css file? (This javascript is not a restful template js.erb file, but rather, a js file included in the manifest.)

Also, is there an elegant way to approach and refactor this?

share|improve this question
    
What's the file's extension you have for your JavaScript is it .js or .js.erb? –  Surya Nov 3 '14 at 11:19
    
js. I should change it to use js.erb? –  ahnbizcad Nov 3 '14 at 11:23
1  
Yes, change it to .js.erb and then: $prod.append("<img class='fx_shadow' id='shd_" + i + "' + src='<%= asset_path('shadow_fx.png') %>' />"); –  Surya Nov 3 '14 at 11:25
1  
I am not if this will work, but also try doing this: $prod.append("<%= image_tag 'shadow_fx.png', :class => 'fx_shadow' %>"); –  Surya Nov 3 '14 at 11:28

2 Answers 2

up vote 1 down vote accepted

Checkout 2.3.3 JavaScript/CoffeeScript and ERB. You need to change .js to .js.erb extension, for example: javascript_filename.js.erb. Then you can use it like so:

$prod.append("<img class='fx_shadow' id='shd_" + i + "' + src='<%= asset_path('shadow_fx.png') %>' />");

or:

var image = $("<%= image_tag 'shadow_fx.png', :class => 'fx_shadow' %>");
image.attr('id', 'shd_'+i);
$prod.append(image);

In second option, you have to make image_tag as image element and then add id attribute to it because i is a JavaScript variable, that's why it has to be added in a separate line.

share|improve this answer
    
I freaken love you thanks so much! –  ahnbizcad Nov 3 '14 at 12:11

Solution 1

Add a function

function imagePath(image){
    return "http://" + window.location.host + "/assets/"+ image;
}

$prod.append("<img class='fx_shadow' id='shd_" + i + "' + src=imagePath(image) />");

Solution 2

Change the file from js to js.erb

$prod.append("<img class='fx_shadow' id='shd_" + i + "' + src='<%= asset_path('shadow_fx.png') %>' />");
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.