Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cache public/assets, and retain old assets until a given expiry time #42

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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