From b73ba1b1012b0b034d385b7731a7f623b4c1bc0a Mon Sep 17 00:00:00 2001 From: Hiroshi Shirosaki Date: Thu, 15 Dec 2016 17:17:41 +0900 Subject: [PATCH] Adds asset_id parameters to assets This invalidates caches in browser like Rails 3. --- config/initializers/10-patches.rb | 51 +++++++++++++++++++++++++++++++++++++ 1 files changed, 51 insertions(+), 0 deletions(-) diff --git a/config/initializers/10-patches.rb b/config/initializers/10-patches.rb index 671b6df..27cc50c 100644 --- a/config/initializers/10-patches.rb +++ b/config/initializers/10-patches.rb @@ -187,3 +187,54 @@ module ActionController end end end + +# Adds asset_id parameters to assets like Rails 3 to invalidate caches in browser +module ActionView + module Helpers + module AssetUrlHelper + @@cache_asset_timestamps = Rails.env.production? + @@asset_timestamps_cache = {} + @@asset_timestamps_cache_guard = Mutex.new + + def asset_path_with_asset_id(source, options = {}) + asset_id = rails_asset_id(source, options) + unless asset_id.blank? + source += "?#{asset_id}" + end + asset_path(source, options) + end + alias :path_to_asset :asset_path_with_asset_id + + def rails_asset_id(source, options = {}) + if asset_id = ENV["RAILS_ASSET_ID"] + asset_id + else + if @@cache_asset_timestamps && (asset_id = @@asset_timestamps_cache[source]) + asset_id + else + extname = compute_asset_extname(source, options) + path = File.join(Rails.public_path, "#{source}#{extname}") + exist = false + if File.exist? path + exist = true + else + path = File.join(Rails.public_path, compute_asset_path("#{source}#{extname}", options)) + if File.exist? path + exist = true + end + end + asset_id = exist ? File.mtime(path).to_i.to_s : '' + + if @@cache_asset_timestamps + @@asset_timestamps_cache_guard.synchronize do + @@asset_timestamps_cache[source] = asset_id + end + end + + asset_id + end + end + end + end + end +end -- 1.7.1