2

我正在使用sinatra/assetpackthin。如何关闭记录资产请求,例如Rails的安静资产?

4

2 回答 2

2

关闭了资产:

module Sinatra
  module QuietLogger

    @extensions = %w(png gif jpg jpeg woff tff svg eot css js coffee scss)

    class << self
      attr_accessor :extensions

      def registered(app)
        ::Rack::CommonLogger.class_eval <<-PATCH
          alias call_and_log call

          def call(env)
            ext = env['REQUEST_PATH'].split('.').last
            if #{extensions.inspect}.include? ext
              @app.call(env)
            else
              call_and_log(env)
            end
          end
        PATCH
      end
    end

  end
end

然后只需在应用程序中注册它:

configure :development
  register QuietLogger
end
于 2013-06-20T06:32:11.043 回答
0

Sinatra 的记录器只是Rack::CommonLogger. 更重要的是,记录器部分是附加到 Sinatra 应用程序的中间件。如果您有自己的基于Rack::CommonLogger模块(或您自己的中间件)的记录器实现,则可以像这样将其添加到 Sinatra:

use MyOwnLogger

我们将对方法进行子类Rack::CommonLogger化和修改,call以确保仅当主体是数据而不是资产时才会发生日志记录。

module Sinatra # This need not be used. But namespacing is a good thing.

  class SilentLogger < Rack::CommonLogger

    def call(env)
      status, header, body = @app.call(env)
      began_at = Time.now
      header = Rack::Utils::HeaderHash.new(header) # converts the headers into a neat Hash

      # we will check if body is an asset and will log only if it is not an asset

      unless is_asset?(body)
        body = BodyProxy.new(body) { log(env, status, header, began_at) }
      end

      [status, header, body]

    end

    private

    def is_asset?(body)
      # If it just plain text, it won't respond to #path method
      return false unless body.respond_to?(:path)
      ext = Pathname.new(body.path).extname
      ext =~ /\.png|\.jp(g|eg)|\.js/ ? true : false
    end

  end
end

然后,在您的应用程序中:

  class App < Sinatra::Base
    use Sinatra::SilentLogger

  end
于 2013-06-20T06:32:46.493 回答