新手问题 Turbolinks 源码记录

i5ting · January 12, 2013 · Last by i5ting replied at January 12, 2013 · 2669 hits

经典源码

地址

https://github.com/rails/turbolinks/blob/master/lib/turbolinks.rb

source

module Turbolinks
  module XHRHeaders
    extend ActiveSupport::Concern

    included do
      alias_method_chain :_compute_redirect_to_location, :xhr_referer
    end

    private
      def _compute_redirect_to_location_with_xhr_referer(options)
        if options == :back && request.headers["X-XHR-Referer"]
          _compute_redirect_to_location_without_xhr_referer(request.headers["X-XHR-Referer"])
        else
          _compute_redirect_to_location_without_xhr_referer(options)
        end
      end

      def set_xhr_current_location
        response.headers['X-XHR-Current-Location'] = request.fullpath
      end
  end

  module Cookies
    private
      def set_request_method_cookie
        cookies[:request_method] = request.request_method
      end
  end

  class Engine < ::Rails::Engine
    initializer :turbolinks_xhr_headers do |config|
      ActionController::Base.class_eval do
        include XHRHeaders, Cookies
        before_filter :set_xhr_current_location, :set_request_method_cookie
      end
    end
  end
end

  • 为了代码清晰,XHRHeaders 和 Cookies 被设计成 2 个 module
  • 通过 extend ActiveSupport::Concern,把 ActiveSupport::Concern 的类方法扩展引入,使之可以调用 included 方法
  • 在 Engine 类中,直接 include 模块 XHRHeaders 和 Cookies

疑问,这种继承为啥是::Rails::Engine?

class Engine < ::Rails::Engine

test

它的 test 也很不错,直接在 test 目录下配置一个 config.ru,这样就可以直接运行 rackup 启动服务,做到了最少依赖。

新手,勉强能看懂点,记录一下

哪位大神来个深入分析?

You need to Sign in before reply, if you don't have an account, please Sign up first.