原创作者: hideto   阅读:862次   评论:0条   更新时间:2011-05-26    
Rails的acts_as_taggable插件在前面每天一剂Rails良药之Tagging一文中已经讲到
今天来看看browser_filters插件,它是三个常用的过滤器的集合:
1,UnicodeContentType,设置charset为"text/html; charset=utf-8"
2,SafariUnicodeFix,解决Safari浏览器的Ajax调用的unicde问题
3,LinkPrefetchingBlock,阻塞Google Web Accelerator或其他东西的prefetch,并返回403 Forbidden

我们可以在ApplicationController里include BrowserFilters或者只include UnicodeContentType, LinkPrefetchingBlock
让我们看看源码
lib/browser_filters.rb:
module BrowserFilters
  def self.included(controller)
    controller.send(:include, LinkPrefetchingBlock, SafariUnicodeFix, UnicodeContentType)
  end
end

BrowserFilters模块简单的告诉include本身的controller去include具体三个filters

lib/link_prefetching_block.rb:
module LinkPrefetchingBlock
  def self.included(controller)
    controller.before_filter(:link_prefetching_block)
  end

  private
    def link_prefetching_block
      if request.env["HTTP_X_MOZ"] == "prefetch"
        render :nothing => true, :status => "403 Forbidden"
        return false
      end
    end
end

LinkPrefetchingBlock模块给include本身的controller加上link_prefetching_block这个before_filter
link_prefetching_block判断如果是GWA等的prefetch则返回403错误

lib/safari_unicode_fix.rb:
module SafariUnicodeFix
  def self.included(controller)
    controller.after_filter(:fix_unicode_for_safari)
  end

  private
    def fix_unicode_for_safari
      if headers["Content-Type"] == "text/html; charset=utf-8" && 
          request.env['HTTP_USER_AGENT'] &&
          request.env['HTTP_USER_AGENT'].include?('AppleWebKit') && 
          String === response.body &&
          !response.body.blank?
        response.body = response.body.to_s.gsub(/([^\x00-\xa0])/u) { |s| "&#x%x;" % $1.unpack('U')[0] rescue $1 }
      end
    end
end

SafariUnicodeFix模块给include本身的controller加上fix_unicode_for_safari这个after_filter

lib/unicode_content_type.rb
module UnicodeContentType
  def self.included(controller)
    controller.after_filter(:set_content_type)
  end

  private
    def set_content_type
      headers["Content-Type"] ||= "text/html; charset=utf-8"
    end
end

UnicodeContentType模块给include本身的controller加上set_content_type这个after_filter
评论 共 0 条 请登录后发表评论

发表评论

您还没有登录,请您登录后再发表评论

文章信息

Global site tag (gtag.js) - Google Analytics