Sha256: 73e4f33b0e843de6017b6dbf86fbb64aeb8ea971f76fa309973ef07a0de92806

Contents?: true

Size: 1.01 KB

Versions: 3

Compression:

Stored size: 1.01 KB

Contents

module Rack
  autoload :RuleSet, 'rack/rewrite/rule'
  autoload :VERSION, 'rack/rewrite/version'
  
  # A rack middleware for defining and applying rewrite rules. In many cases you 
  # can get away with rack-rewrite instead of writing Apache mod_rewrite rules.  
  class Rewrite
    def initialize(app, given_options = {}, &rule_block)
      options = {
          :klass => RuleSet,
          :options => {}
      }.merge(given_options)
      @app = app
      @rule_set = options[:klass].new(options[:options])
      @rule_set.instance_eval(&rule_block) if block_given?
    end
    
    def call(env)
      if matched_rule = find_first_matching_rule(env)
        rack_response = matched_rule.apply!(env)
        # Don't invoke the app if applying the rule returns a rack response
        return rack_response unless rack_response === true
      end
      @app.call(env)
    end
        
    private
      def find_first_matching_rule(env) #:nodoc:
        @rule_set.rules.detect { |rule| rule.matches?(env) }
      end    
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
rack-rewrite-1.5.1 lib/rack/rewrite.rb
rack-rewrite-1.5.0 lib/rack/rewrite.rb
rack-rewrite-1.4.1 lib/rack/rewrite.rb