Skip to content

Commit

Permalink
Add support for lambda matchers.
Browse files Browse the repository at this point in the history
  • Loading branch information
joshwlewis committed Jul 27, 2013
1 parent e1db257 commit eb3a687
Show file tree
Hide file tree
Showing 3 changed files with 117 additions and 83 deletions.
49 changes: 28 additions & 21 deletions README.markdown
@@ -1,6 +1,6 @@
# rack-rewrite

A rack middleware for defining and applying rewrite rules. In many cases you
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.

## Usage Examples
Expand All @@ -12,7 +12,7 @@ can get away with rack-rewrite instead of writing Apache mod_rewrite rules.
## Usage Details

### Sample rackup file

```ruby
gem 'rack-rewrite', '~> 1.2.1'
require 'rack/rewrite'
Expand Down Expand Up @@ -73,7 +73,7 @@ behaves the same as 303.

### Rebuild of existing site in a new technology

It's very common for sites built in older technologies to be rebuilt with the
It's very common for sites built in older technologies to be rebuilt with the
latest and greatest. Let's consider a site that has already established quite
a bit of "google juice." When we launch the new site, we don't want to lose
that hard-earned reputation. By writing rewrite rules that issue 301's for
Expand Down Expand Up @@ -124,11 +124,11 @@ RewriteRule ^.*$ /system/maintenance.html [L]
```

This rewrite rule says to render a maintenance page for all non-asset requests
if the maintenance file exists. In capistrano, you can quickly upload a
if the maintenance file exists. In capistrano, you can quickly upload a
maintenance file using:

`cap deploy:web:disable REASON=upgrade UNTIL=12:30PM`

We can replace the mod_rewrite rules with the following Rack::Rewrite rule:

```ruby
Expand All @@ -147,7 +147,7 @@ send_file /(.*)$(?<!css|png|jpg)/, maintenance_file, :if => Proc.new { |rack_env
}
```

For those using the oniguruma gem with their ruby 1.8 installation, you can
For those using the oniguruma gem with their ruby 1.8 installation, you can
get away with:

```ruby
Expand All @@ -161,9 +161,9 @@ send_file Oniguruma::ORegexp.new("(.*)$(?<!css|png|jpg)"), maintenance_file, :if

### :rewrite

Calls to #rewrite will simply update the PATH_INFO, QUERY_STRING and
REQUEST_URI HTTP header values and pass the request onto the next chain in
the Rack stack. The URL that a user's browser will show will not be changed.
Calls to #rewrite will simply update the PATH_INFO, QUERY_STRING and
REQUEST_URI HTTP header values and pass the request onto the next chain in
the Rack stack. The URL that a user's browser will show will not be changed.
See these examples:

```ruby
Expand All @@ -172,14 +172,14 @@ rewrite %r{/wiki/(\w+)_\w+}, '/$1' # [2]
```

For [1], the user's browser will continue to display /wiki/John_Trupiano, but
the actual HTTP header values for PATH_INFO and REQUEST_URI in the request
the actual HTTP header values for PATH_INFO and REQUEST_URI in the request
will be changed to /john for subsequent nodes in the Rack stack. Rails
reads these headers to determine which routes will match.

Rule [2] showcases the use of regular expressions and substitutions. [2] is a
Rule [2] showcases the use of regular expressions and substitutions. [2] is a
generalized version of [1] that will match any /wiki/FirstName_LastName URL's
and rewrite them as the first name only. This is an actual catch-all rule we
applied when we rebuilt our website in September 2009
and rewrite them as the first name only. This is an actual catch-all rule we
applied when we rebuilt our website in September 2009
( http://www.smartlogicsolutions.com ).

### :r301, :r302, :r303, :r307
Expand All @@ -193,7 +193,7 @@ r301 '/wiki/John_Trupiano', '/john' # [1]
r301 %r{/wiki/(.*)}, 'http://www.google.com/?q=$1' # [2]
```

Recall that rules are interpreted from top to bottom. So you can install
Recall that rules are interpreted from top to bottom. So you can install
"default" rewrite rules if you like. [2] is a sample default rule that
will redirect all other requests to the wiki to a google search.

Expand Down Expand Up @@ -228,7 +228,7 @@ This rule will only match when the hostname is "facerecognizer.com"

### :headers

Using the :headers option you can set custom response headers e.g. for HTTP
Using the :headers option you can set custom response headers e.g. for HTTP
caching instructions.

```ruby
Expand All @@ -250,7 +250,7 @@ send_file /^.+\.(?:ico|jpg|jpeg|png|gif|)$/,

### :method

Using the :method option you can restrict the matching of a rule by the HTTP
Using the :method option you can restrict the matching of a rule by the HTTP
method of a given request.

```ruby
Expand All @@ -264,13 +264,13 @@ r302 "/players", "/no_longer_available.html?message=No&longer&supported", :metho
### :if

Using the :if option you can define arbitrary rule guards. Guards are any
object responding to #call that return true or false indicating whether the
rule matches. The following example demonstrates how the presence of a
object responding to #call that return true or false indicating whether the
rule matches. The following example demonstrates how the presence of a
maintenance page on the filesystem can be utilized to take your site(s) offline.

```ruby
maintenance_file = File.join(RAILS_ROOT, 'public', 'system', 'maintenance.html')
x_send_file /.*/, maintenance_file, :if => Proc.new { |rack_env|
x_send_file /.*/, maintenance_file, :if => Proc.new { |rack_env|
File.exists?(maintenance_file)
}
```
Expand All @@ -290,7 +290,7 @@ This will not match the relative URL /features but would match /features.xml.

### Keeping your querystring

When rewriting a URL, you may want to keep your querystring in tact (for
When rewriting a URL, you may want to keep your querystring in tact (for
example if you're tracking traffic sources). You will need to include a
capture group and substitution pattern in your rewrite rule to achieve this.

Expand All @@ -303,7 +303,7 @@ will substitute the querystring back into the rewritten URL (via `$1`).

### Arbitrary Rewriting

All rules support passing a Proc as the second argument allowing you to
All rules support passing a Proc as the first or second argument allowing you to
perform arbitrary rewrites. The following rule will rewrite all requests
received between 12AM and 8AM to an unavailable page.

Expand All @@ -313,6 +313,13 @@ received between 12AM and 8AM to an unavailable page.
}
```

This rule will redirect all requests paths starting with a current date
string to /today.html

```ruby
r301 lambda { "/#{Time.current.strftime(%m%d%Y)}.html" }, '/today.html'
```

## Contribute

rack-rewrite is maintained by [@travisjeffery](http://github.com/travisjeffery).
Expand Down
7 changes: 6 additions & 1 deletion lib/rack/rewrite/rule.rb
Expand Up @@ -99,7 +99,7 @@ def add_rule(method, from, to, options = {}) #:nodoc:

# TODO: Break rules into subclasses
class Rule #:nodoc:
attr_reader :rule_type, :from, :to, :options
attr_reader :rule_type, :to, :options
def initialize(rule_type, from, to, options={}) #:nodoc:
@rule_type, @from, @to, @options = rule_type, from, to, normalize_options(options)
end
Expand All @@ -111,6 +111,11 @@ def matches?(rack_env) #:nodoc:
self.match_options?(rack_env) && string_matches?(path, self.from)
end

def from
return @static_from if @static_from
@from.respond_to?(:call) ? @from.call : @static_from = @from
end

# Either (a) return a Rack response (short-circuiting the Rack stack), or
# (b) alter env as necessary and return true
def apply!(env) #:nodoc:
Expand Down

0 comments on commit eb3a687

Please sign in to comment.