Methods for minifying and optimizing CSS.
Constants
ENGINES | = | [:weak, :cssmin] | A list of supported minification engine names. |
Public class methods
Given a string containing CSS, appends each referenced asset’s last commit ID to its URL, e.g., background: url(/images/foo.png?ab12cd3). This enables cache busting: If the user’s browser has cached a copy of foo.png from a previous deployment, this new URL forces the browser to ignore that cache and request the latest version.
# File lib/asset_hat/css.rb, line 43 43: def self.add_asset_commit_ids(css) 44: update_css_urls(css, %w[images htc]) do |src, quote| 45: # Get absolute path 46: filepath = File.join(ASSETS_DIR, src) 47: 48: # Convert to relative path 49: filepath.sub!(/^#{FileUtils.pwd}#{File::SEPARATOR}/, '') 50: 51: commit_id = AssetHat.last_commit_id(filepath) 52: if commit_id.present? 53: "url(#{quote}#{src}#{src =~ /\?/ ? '&' : '?'}#{commit_id}#{quote})" 54: else 55: "url(#{quote}#{src}#{quote})" 56: end 57: end 58: end
Arguments:
- A string containing CSS;
- A string containing the app’s asset host, e.g., ‘http://cdn%d.example.com’. This value is typically taken from config.action_controller.asset_host in the app’s config/environments/production.rb.
An asset host is added to every image URL in the CSS, e.g., background: url(http://cdn2.example.com/images/foo.png); if %d in the asset host, it is replaced with an arbitrary number in 0-3, inclusive.
Options:
- ssl
- Set to true to simulate a request via SSL. Defaults to false.
# File lib/asset_hat/css.rb, line 77 77: def self.add_asset_hosts(css, asset_host, options={}) 78: return css if asset_host.blank? 79: 80: options.reverse_merge!(:ssl => false) 81: 82: update_css_urls(css, %w[images]) do |src, quote| 83: computed_asset_host = AssetHat.compute_asset_host( 84: asset_host, src, options.slice(:ssl)) 85: "url(#{quote}#{computed_asset_host}#{src}#{quote})" 86: end 87: end
Returns the expected path for the minified version of a CSS asset:
AssetHat::CSS.min_filepath('public/stylesheets/bundles/application.css') # => 'public/stylesheets/bundles/application.min.css'
# File lib/asset_hat/css.rb, line 14 14: def self.min_filepath(filepath) 15: AssetHat.min_filepath(filepath, 'css') 16: end
Accepts a string of CSS, and returns that CSS minified. Options:
- engine
- Default is :cssmin; see Engines.cssmin. Allowed values are in ENGINES.
# File lib/asset_hat/css.rb, line 23 23: def self.minify(input_string, options={}) 24: options.reverse_merge!(:engine => :cssmin) 25: 26: engine = options[:engine].to_sym 27: unless ENGINES.include?(engine) 28: raise %{ 29: Unknown CSS minification engine '#{engine}'. 30: Allowed: #{ENGINES.map{ |e| "'#{e}'" }.join(', ')} 31: }.strip.gsub(/\s+/, ' ') and return 32: end 33: 34: AssetHat::CSS::Engines.send(engine, input_string).strip 35: end