Class: Middleman::Extensions::AssetHash

Inherits:
Middleman::Extension show all
Defined in:
lib/middleman-more/extensions/asset_hash.rb

Defined Under Namespace

Classes: Middleware

Instance Attribute Summary

Attributes inherited from Middleman::Extension

#app, #options

Instance Method Summary collapse

Methods inherited from Middleman::Extension

activate, activated_extension, after_extension_activated, clear_after_extension_callbacks, config, extension_name, helpers, option, register

Constructor Details

#initialize(app, options_hash = {}, &block) ⇒ AssetHash

Returns a new instance of AssetHash.



7
8
9
10
11
12
13
# File 'lib/middleman-more/extensions/asset_hash.rb', line 7

def initialize(app, options_hash={}, &block)
  super

  require 'digest/sha1'
  require 'rack/test'
  require 'uri'
end

Instance Method Details

#after_configurationObject



15
16
17
18
19
20
# File 'lib/middleman-more/extensions/asset_hash.rb', line 15

def after_configuration
  # Allow specifying regexes to ignore, plus always ignore apple touch icons
  @ignore = Array(options.ignore) + [/^apple-touch-icon/]

  app.use Middleware, exts: options.exts, middleman_app: app, ignore: @ignore
end

#ignored_resource?(resource) ⇒ Boolean

Returns:

  • (Boolean)


55
56
57
# File 'lib/middleman-more/extensions/asset_hash.rb', line 55

def ignored_resource?(resource)
  @ignore.any? { |ignore| Middleman::Util.path_match(ignore, resource.destination_path) }
end

#manipulate_resource_list(resources)

This method returns an undefined value.

Update the main sitemap resource list



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/middleman-more/extensions/asset_hash.rb', line 24

def manipulate_resource_list(resources)
  @rack_client ||= ::Rack::Test::Session.new(app.class.to_rack_app)

  # Process resources in order: binary images and fonts, then SVG, then JS/CSS.
  # This is so by the time we get around to the text files (which may reference
  # images and fonts) the static assets' hashes are already calculated.
  resources.sort_by do |a|
    if %w(.svg).include? a.ext
      0
    elsif %w(.js .css).include? a.ext
      1
    else
      -1
    end
  end.each(&method(:manipulate_single_resource))
end

#manipulate_single_resource(resource) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/middleman-more/extensions/asset_hash.rb', line 41

def manipulate_single_resource(resource)
  return unless options.exts.include?(resource.ext)
  return if ignored_resource?(resource)
  return if resource.ignored?

  # Render through the Rack interface so middleware and mounted apps get a shot
  response = @rack_client.get(URI.escape(resource.destination_path), {},  'bypass_asset_hash' => 'true')
  raise "#{resource.path} should be in the sitemap!" unless response.status == 200

  digest = Digest::SHA1.hexdigest(response.body)[0..7]

  resource.destination_path = resource.destination_path.sub(/\.(\w+)$/) { |ext| "-#{digest}#{ext}" }
end