在CSS中的图像上的Rails时间戳

bra*_*rad 10 apache ruby-on-rails

所以Rails时间戳很棒.我正在使用它将expires标头添加到以10位数时间戳结尾的所有文件.然而,我的大多数图像都在我的CSS中引用.有没有人遇到任何允许将时间戳添加到CSS引用图像的方法,或者实现此目的的一些时髦的重写规则?我喜欢我站点中的所有图像,内联和css都有这个时间戳,所以我可以告诉浏览器缓存它们,但是在文件本身发生变化时刷新.

我在网上找不到任何关于此的内容,我无法相信这不是一个更常讨论的话题.

我不认为我的设置会很重要,因为根据10位数的时间戳,实际到期将有希望以相同的方式发生,但是如果重要的话,我正在使用apache来提供所有静态内容

Ben*_*use 5

我一直在使用资产打包器,最后我编辑了插件的compress_css方法来解决这个问题.我基本上只是css中图像的正则表达式,并插入当前时间戳:

timestamp = Time.now.to_s.gsub(/\D/, '')
source.gsub!(/url\((['"])(.+)(['"])\)/) do
  open, file, close = $1, $2, $3
  if file =~ /.\.(ico|css|js|gif|jpe?g|png)/
    "url(#{open}#{file}?#{timestamp}#{close})"
  else
    "url(#{open}#{file}#{close})"
  end
end
Run Code Online (Sandbox Code Playgroud)

这样,每当我部署时,压缩的css图像都包含附加的时间戳.这种方法的缺点是每个图像都没有自己的时间戳,因此每次部署新的css时,所有的css图像都会"过期".除非经常部署css,否则总比没有好.


小智 4

您可以通过获取文件修改时间来附加每个图像文件的实际时间戳,如下所示:

    source.gsub!(/url\((['"]*)(.+)(['"]*)\)/) do
      open, file, close = $1, $2, $3
      css_dir = File.join(RAILS_ROOT,"public/stylesheets")
      timestamp = ''
      FileUtils.cd(css_dir) do 
        if file =~ /^\// # absolute path
          f = File.new(RAILS_ROOT + "/public" + file)
        else # relative path
          f = File.new(file)
        end
        timestamp = f.mtime.to_i.to_s
      end

      if file =~ /.\.(ico|css|js|gif|jpe?g|png)/
        "url(#{open}#{file}?#{timestamp}#{close})"
      else
        "url(#{open}#{file}#{close})"
      end
    end
Run Code Online (Sandbox Code Playgroud)

(可能有一种更优雅的方式来写这个,我的红宝石排骨仍然很弱!)但是现在 hack 变得丑陋了......你会认为会有一种更像 Rails 的方式来做到这一点。