Skip to content

Instantly share code, notes, and snippets.

@devkinetic
Last active July 1, 2016 17:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devkinetic/7f6d340c2d330119db300c2e1f8b95a4 to your computer and use it in GitHub Desktop.
Save devkinetic/7f6d340c2d330119db300c2e1f8b95a4 to your computer and use it in GitHub Desktop.
Rails 4 static site generation
# config/application.rb
module AssetsInitializers
class Railtie < Rails::Railtie
initializer "assets_initializers.initialize_rails",
:group => :assets do |app|
require "#{Rails.root}/config/initializers/sprockets_patch.rb"
end
end
end
# lib/tasks/assets.rake
Rake::Task["assets:precompile"].enhance do
Rake::Task["assets:regurgitate_digested_assets"].invoke
end
Rake::Task["assets:clean"].clear
namespace :assets do
logger = Logger.new($stderr)
task :regurgitate_digested_assets => :environment do
manifest_path = Dir.glob(File.join(Rails.root, 'public/assets/.sprockets-manifest-*.json')).first
manifest_data = JSON.load(File.new(manifest_path))
regurgitated_assets = {}
manifest_data["assets"].each do |logical_path, digested_path|
full_digested_path = File.join(Rails.root, 'public/assets', digested_path)
full_nondigested_path = File.join(Rails.root, 'public/assets', logical_path)
logger.info "(Regurgitate) Copying to #{full_nondigested_path}"
regurgitated_assets[logical_path] = logical_path
if File.extname(full_digested_path) == '.css'
logger.info "(Regurgitate) Removing digest hashes from css file"
css = File.read(full_digested_path)
digests_removed = css.gsub(/(-{1}[a-z0-9]{32}*\.{1}){1}/, '.')
File.open(full_nondigested_path, "w") { |file| file.puts digests_removed }
else
# Use FileUtils.copy_file with true third argument to copy
# file attributes (eg mtime) too, as opposed to FileUtils.cp
FileUtils.copy_file full_digested_path, full_nondigested_path, true
end
end
manifest_data["assets"] = manifest_data["assets"].merge(regurgitated_assets)
File.open(manifest_path, 'w') { |file| file.write(manifest_data.to_json) }
end
task :clean => :environment do
logger.info "Skipping asset cleaning, we like it dirty!"
end
end
# config/environments/production.rb
#
# Can also be set to false, but this is better
config.assets.digest = !ENV['RAILS_DISABLE_DIGEST'].present?
# config/initializers/sprockets_patch.rb
#
# We don't want to compute the paths anymore, just return them
Sprockets::Rails::Helper.class_eval do
def compute_asset_path(path, options = {})
File.join(assets_prefix, path)
end
end
@devkinetic
Copy link
Author

Build the site via:

wget -mnH -k --html-extension http://codebase.herokuapp.com/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment