Skip to content

Commit

Permalink
Cache public/assets, and retain old assets until a given expiry time
Browse files Browse the repository at this point in the history
  • Loading branch information
ndbroadbent committed Oct 28, 2012
1 parent a815917 commit 6821cb7
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions lib/language_pack/rails3.rb
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ def run_assets_precompile_rake_task
if File.exists?("public/assets/manifest.yml")
puts "Detected manifest.yml, assuming assets were compiled locally"
else
FileUtils.mkdir_p('public')
cache_load "public/assets"
update_mtimes_for_current_assets

ENV["RAILS_GROUPS"] ||= "assets"
ENV["RAILS_ENV"] ||= "production"

Expand All @@ -53,6 +57,9 @@ def run_assets_precompile_rake_task
if $?.success?
log "assets_precompile", :status => "success"
puts "Asset precompilation completed (#{"%.2f" % time}s)"

remove_expired_assets
cache_store "public/assets"
else
log "assets_precompile", :status => "failure"
puts "Precompiling assets failed, enabling runtime asset compilation"
Expand All @@ -65,6 +72,35 @@ def run_assets_precompile_rake_task
end
end

# Updates the mtimes for current assets, which marks the time when they were last deployed.
# This is done so that old assets are expired correctly, based on their mtime.
def update_mtimes_for_current_assets
return false unless File.exists?("public/assets/manifest.yml")

digests = YAML.load_file("public/assets/manifest.yml")
# Iterate over all assets, including gzipped versions
digests.flatten.flat_map {|a| [a, "#{a}.gz"] }.each do |asset|
rel_path = File.join('public/assets', asset)
File.utime(Time.now, Time.now, rel_path) if File.exist?(rel_path)
end
end

# Removes assets that haven't been in use for a given period of time (defaults to 1 week.)
# The expiry time can be configured by setting the env variable EXPIRE_ASSETS_AFTER,
# which is the number of seconds to keep unused assets.
def remove_expired_assets
expire_after = (ENV["EXPIRE_ASSETS_AFTER"] || (3600 * 24 * 7)).to_i

Dir.glob('public/assets/**/*').each do |asset|
next if File.directory?(asset)
# Remove asset if older than expire_after time
if File.mtime(asset) < (Time.now - expire_after)
puts "Removing expired asset: #{asset.sub(%r{.*/public/assets/}, '')}"
FileUtils.rm_f asset
end
end
end

# setup the database url as an environment variable
def setup_database_url_env
ENV["DATABASE_URL"] ||= begin
Expand Down

0 comments on commit 6821cb7

Please sign in to comment.