views:

619

answers:

3

I'm using a transparent PNG with the Google IE fix library. This fix only works on images urls that end in "-trans.png".

Rails' timestamp-based caching is causing problems with this. When I use image_path() to generate the URL for the image, it appends the file's last-modified timestamp to the image's query string. Since the URL no longer ends in "-trans.png" (instead ending in "?" plus a long integer), Google's javascript fails to activate.

I don't want to disable asset caching entirely; just on certain images. I also don't want to hardcode a relative URL to the root of the server. I want to use Rails to generate the URL correctly if the site is deployed to the server root or an (unknown) subdirectory.

What options do I have?

+1  A: 
# apologies I'm doing this off the cuff and haven't run-tested this code
alias_method_chain :image_path, :google_sense

def image_path_with_google_sense(source)
  raw_image_path = image_path_without_google_sense(source)
  if source.end_with?('-trans.png')
    # strip off the time stamp
    raw_image_path.split('?').first
  else
    raw_image_path
  end
end
Teflon Ted
I was hoping to avoid having to strip off the query string, but this is the only answer so far. Thanks :-)
Craig Walker
A: 

I came up with a completely different way of solving this problem, using jQuery to replace the appropriate URLs:

jQuery(document).ready(function($) {
  $("img.logo").attr("src", "/images/logo-trans.png");
});

The benefit of this is that I can make the cache-stripping IE-only using IE's conditional HTML comments.

Craig Walker
Interesting but your example code has a couple issues like replacing every IMG tag with the class "logo" on the page which is fine if you're the only person working on the code but could be a big WTF moment if some other designer make the faux pas of using the same tag/class combination for another image.Also this only works for one particular image. You implied in your question that you had multiple images you wanted to "fix", so you might be better off with some pattern matching on the "src" value, which I think jQuery can do.
Teflon Ted
Yeah you can use this: $("img[src*='-trans.png']")
Teflon Ted
Yup, you're right there.
Craig Walker
A: 

The easiest solution is probably just add a special case when the asset tag is appended to the file name to make it work correctly, for example:

   def rewrite_asset_path(source)
      asset_id = rails_asset_id(source)
      if asset_id.blank?
        source
      elsif source.end_with?("-trans.png")
        "#{source[0..-11]}.#{asset_id}-trans.png"
      else
        source + "?#{asset_id}"
      end
    end

This way any of the images will have their paths rewritten to have the cache-buster inline. This still works as you would expect it to.

jkupferman