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

Inherits:
Object
  • Object
show all
Defined in:
middleman-more/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

- (Middleware) initialize(app, options = {})

A new instance of Middleware



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

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

Instance Method Details

- (Object) call(env)



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
# File 'middleman-more/lib/middleman-more/extensions/asset_hash.rb', line 65

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

  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|
        asset_path = $2
        relative_path = Pathname.new(asset_path).relative?

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

        if 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

          "#{$1}#{replacement_path}"
        else
          match
        end
      end

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