Rails asset pipeline and digest values

送分小仙女□ 提交于 2019-12-03 14:47:31

Grabbed from rails guides

When a filename is unique and based on its content, HTTP headers can be set to encourage caches everywhere (whether at CDNs, at ISPs, in networking equipment, or in web browsers) to keep their own copy of the content. When the content is updated, the fingerprint will change. This will cause the remote clients to request a new copy of the content. This is generally known as cache busting.

The technique that Rails uses for fingerprinting is to insert a hash of the content into the name, usually at the end. For example a CSS file global.css could be renamed with an MD5 digest of its contents

The accepted answer is not quite true. We build static assets for our staging, demo and production servers, and the same asset is given different digest values in each case.

It turns out that the Rails environment is also being taken into consideration. Sprockets creates the digest as follows:

# Sprockets::Environment::initialize
@digest_class = ::Digest::MD5

# Sprockets::Base::digest
@digest ||= digest_class.new.update(VERSION).update(version.to_s)

# Sprockets::Base::file_digest(path)
digest.file(path.to_s)

# Sprockets::Asset::initialize
@digest = environment.file_digest(pathname).hexdigest

Rails hooks into Sprockets as follows:

# Sprockets::Railtie
app.assets = Sprockets::Environment.new(app.root.to_s) do |env|
  env.version = ::Rails.env + "-#{config.assets.version}"
  ...
end

So rails is creating a Sprockets environment that has a version equal to the Rails environment, and Sprockets uses the version when creating the digest class.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!