Class: Middleman::Extensions::AssetHash::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/middleman-more/extensions/asset_hash.rb

Overview

The asset hash middleware is responsible for rewriting references to assets to include their new, hashed name.

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ Middleware

Returns a new instance of Middleware.



57
58
59
60
61
62
63
# File 'lib/middleman-more/extensions/asset_hash.rb', line 57

def initialize(app, options={})
  @rack_app        = app
  @exts            = options[:exts]
  @ignore          = options[:ignore]
  @exts_regex_text = @exts.map {|e| Regexp.escape(e) }.join('|')
  @middleman_app   = options[:middleman_app]
end

Instance Method Details

#call(env) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/middleman-more/extensions/asset_hash.rb', line 65

def call(env)
  status, headers, response = @rack_app.call(env)

  # We don't want to use this middleware when rendering files to figure out their hash!
  return [status, headers, response] if env["bypass_asset_hash"]

  path = @middleman_app.full_path(env["PATH_INFO"])
  dirpath = Pathname.new(File.dirname(path))

  if path =~ /(^\/$)|(\.(htm|html|php|css|js)$)/
    body = ::Middleman::Util.extract_response_text(response)

    if body
      # TODO: This regex will change some paths in plan HTML (not in a tag) - is that OK?
      body.gsub! /([=\'\"\(]\s*)([^\s\'\"\)]+(#{@exts_regex_text}))/ do |match|
        opening_character = $1
        asset_path = $2

        relative_path = Pathname.new(asset_path).relative?

        asset_path = dirpath.join(asset_path).to_s if relative_path

        if @ignore.any? { |r| asset_path.match(r) }
          match
        elsif asset_page = @middleman_app.sitemap.find_resource_by_path(asset_path)
          replacement_path = "/#{asset_page.destination_path}"
          replacement_path = Pathname.new(replacement_path).relative_path_from(dirpath).to_s if relative_path

          "#{opening_character}#{replacement_path}"
        else
          match
        end
      end

      status, headers, response = Rack::Response.new(body, status, headers).finish
    end
  end
  [status, headers, response]
end