Class: Middleman::Extensions::RelativeAssets

Inherits:
Middleman::Extension show all
Defined in:
lib/middleman-core/extensions/relative_assets.rb

Overview

Relative Assets extension

Constant Summary

Constants included from Contracts

Contracts::PATH_MATCHER

Instance Attribute Summary

Attributes inherited from Middleman::Extension

#app, #options

Instance Method Summary collapse

Methods inherited from Middleman::Extension

activated_extension, #add_exposed_to_context, #after_build, #after_configuration, after_extension_activated, #after_extension_activated, #before_build, #before_configuration, clear_after_extension_callbacks, config, expose_to_application, expose_to_config, expose_to_template, helpers, #manipulate_resource_list, option, resources

Methods included from Contracts

#Contract

Constructor Details

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

Returns a new instance of RelativeAssets.



9
10
11
12
13
# File 'lib/middleman-core/extensions/relative_assets.rb', line 9

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

  require 'middleman-core/middleware/inline_url_rewriter'
end

Instance Method Details

#readyObject



15
16
17
18
19
20
21
22
23
# File 'lib/middleman-core/extensions/relative_assets.rb', line 15

def ready
  app.use ::Middleman::Middleware::InlineURLRewriter,
          id: :asset_hash,
          url_extensions: options.exts,
          source_extensions: options.sources,
          ignore: options.ignore,
          middleman_app: app,
          proc: method(:rewrite_url)
end

#rewrite_url(asset_path, dirpath, request_path) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/middleman-core/extensions/relative_assets.rb', line 39

def rewrite_url(asset_path, dirpath, request_path)
  uri = ::Addressable::URI.parse(asset_path)

  return if uri.path[0..0] != '/'

  relative_path = uri.host.nil?

  full_asset_path = if relative_path
    dirpath.join(asset_path).to_s
  else
    asset_path
  end

  current_dir = Pathname(request_path).dirname
  result = Pathname(full_asset_path).relative_path_from(current_dir).to_s

  result
end