Middleman のプレビューサーバーの 404 Not Found 画面をカスタマイズする

現在、開発している AngularJS アプリケーションは、土台を Middleman で作り、Amazon S3静的ウェブサイトホスティング を使って公開する仕組みになっており、エラーページにロジックを書く必要がありました。 (後述します)

Middlemanプレビューサーバーの 404 Not Found 画面は、上記の画像の様なそっけないもので、ライブラリにべた書きされています。

参照: middleman-core/core_extensions/request.rb

これでは、エラーページの確認が難しいので、この 404 画面をカスタマイズする機能拡張を書きました。

config.rb (抜粋)

require './lib/middleman/extensions/custom_not_found'
activate :custom_not_found

lib/middleman/extensions/custom_not_found.rb

require 'middleman-core'

class CustomNotFound < ::Middleman::Extension
  option :error_page, 'error.html', 'Path for error page. `error.html` by default.'

  def initialize(app, options_hash={}, &block)
    super
    error_page = options.error_page
    app.before do
      path = ::Middleman::Util.normalize_path req.path
      path = 'index.html' if path.empty?
      sitemap.ensure_resource_list_updated!
      unless sitemap.find_resource_by_destination_path path
        paths = sitemap.instance_variable_get :@_lookup_by_destination_path
        paths[path] = paths[error_page]
      end
      true
    end
  end
end

::Middleman::Extensions.register(:custom_not_found, CustomNotFound)

error_page.html.slim

Slim テンプレートには以下の様な JavaScript が記述されています。

javascript:
  document.location.href = "#{config[:http_prefix]}#" + document.location.pathname

HTML レンダリング結果は以下の様になります。

<script type="text/javascript">
  document.location.href = "/#" + document.location.pathname
</script>

S3 設定

この error.htmlAmazon S3 のコンソール上でエラーページとして設定しておくことで、HTML5 modeAngularJS アプリケーションで、リロードされた場合も、/index.html に実装されている本体に転送し、リロード前の状態を復元することが可能になります。

comments powered by Disqus