class Rack::Prerender::Constraint

Constants

CRAWLER_USER_AGENTS
EXTENSIONS_TO_IGNORE

Attributes

blacklist[R]
crawler_user_agents[R]
extensions_to_ignore[R]
whitelist[R]

Public Class Methods

new(opts = {}) click to toggle source
# File lib/rack/prerender/constraint.rb, line 6
def initialize(opts = {})
  @blacklist            = cast_to_regexp(opts[:blacklist], escape: false)
  @whitelist            = cast_to_regexp(opts[:whitelist], escape: false)
  @crawler_user_agents  = cast_to_regexp(opts[:crawler_user_agents] || CRAWLER_USER_AGENTS)
  @extensions_to_ignore = cast_to_regexp(opts[:extensions_to_ignore] || EXTENSIONS_TO_IGNORE)
end

Public Instance Methods

matches?(env) click to toggle source

This is run on every request, so performance matters here.

# File lib/rack/prerender/constraint.rb, line 14
def matches?(env)
  return false if env['REQUEST_METHOD'] != 'GET' ||
                  env['HTTP_X_PRERENDER'] ||
                  (user_agent = env['HTTP_USER_AGENT']).nil?

  query = env['QUERY_STRING'].to_s
  return false unless crawler_user_agents.match?(user_agent) ||
                      env['HTTP_X_BUFFERBOT'] ||
                      query.include?('_escaped_fragment_')

  path = env['SCRIPT_NAME'].to_s + env['PATH_INFO'].to_s
  fullpath = query.empty? ? path : "#{path}?#{query}"
  return false if extensions_to_ignore.match?(fullpath)
  return false if whitelist && !whitelist.match?(fullpath)
  return false if blacklist && (blacklist.match?(fullpath) ||
                                blacklist.match?(env['HTTP_REFERER'].to_s))

  true
end

Private Instance Methods

cast_to_regexp(list_arg, escape: true) click to toggle source
# File lib/rack/prerender/constraint.rb, line 36
def cast_to_regexp(list_arg, escape: true)
  regexp =
    case list_arg
    when Regexp, nil
      list_arg
    when Array
      escape ? Regexp.union(list_arg) : Regexp.new(list_arg.join('|'))
    else
      Regexp.new(escape ? Regexp.escape(list_arg) : list_arg)
    end
  regexp && Regexp.new(regexp.source, Regexp::IGNORECASE)
end