Asset urls without cache timestamps in Rails

I am using transparent PNG with google IE fix library . This fix only works with image URLs that end in "-trans.png".

Rails timestamp caching causes problems with this. When I use image_path () to generate a URL for an image, it adds the timestamp of the last modified file to the image query string. Since the URL no longer ends with "-trans.png" (instead ends with "?" Plus a long integer), Google javascript is not activated.

I don't want to completely disable resource caching ; just on certain images. I also don't want to hardcode the server root relative url. 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?

+2


source to share


3 answers


# 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

      



+1


source


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

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

      



The advantage of this is that I can only do IE caching with IE conditional HTML comments.

0


source


The simplest solution is probably just adding a special case where the resource tag is appended to the filename to make it work correctly, like this:

   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

      

Thus, paths will be recorded on any of the images in order to have a built-in cache buster. This still works as you'd expect.

0


source







All Articles