Sha256: 402045a7b53d0b34ed7c57268aa5fcbea4986a6ce41c9946c7ba8178dd14579d

Contents?: true

Size: 1.41 KB

Versions: 1

Compression:

Stored size: 1.41 KB

Contents

require 'rack'

module Rack
  class DenyIE
    
    DEFAULT_TEMPLATE_PATH = ::File.join(::File.dirname(__FILE__), 'html', 'default.html')
    
    def initialize(app, options = {})
      @app = app
      @options = { :min_version => 6, :template_path => DEFAULT_TEMPLATE_PATH, :redirect_url => nil }.merge options
    end
  
    def call(env)
      status, @headers, content = @app.call(env)
      is_browser_supported?(env) && is_content_html? ? act_on_ie : @app.call(env)
    end
    
    private 
    
    def is_browser_supported?(env)
      env["HTTP_USER_AGENT"].match(/MSIE [0-#{@options[:min_version]}]\.[0-9][0-9]?/)
    end
    
    def is_content_html?
      @headers["Content-Type"] && @headers["Content-Type"].include?("text/html")
    end
   
    def act_on_ie
      should_redirect? ? redirect_browser : display_template
    end
    
    def should_redirect?
      !@options[:redirect_url].nil? && @options[:redirect_url].match(/(^$)|(^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$)/ix)
    end
    
    def redirect_browser
      [302, { 'Location' => @options[:redirect_url] }, "Your browser is unsupported." ]
    end
    
    def display_template
      response = ::File.read(@options[:template_path]) # TODO: Add check to see if template points to an actual file
      @headers['Content-Length'] = Rack::Utils.bytesize(response.to_s).to_s
      [200, @headers, response]
    end
    
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rack-denyie-0.1.0 lib/rack-denyie.rb