Eigen Class
Posts: 358
Nickname: eigenclass
Registered: Oct, 2005
|
Eigenclass is a hardcore Ruby blog.
|
|
|
|
URL rewriting with WEBrick
|
Posted: Jan 16, 2007 5:06 AM
|
|
|
This post originated from an RSS feed registered with Ruby Buzz
by Eigen Class.
|
Original Post: URL rewriting with WEBrick
Feed Title: Eigenclass
Feed URL: http://feeds.feedburner.com/eigenclass
Feed Description: Ruby stuff --- trying to stay away from triviality.
|
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Eigen Class
Latest Posts From Eigenclass
|
|
WEBrick isn't as fashionable as it once was, but it's still invaluable for
development and testing. I recently needed it to handle rewrite rules, and
google didn't return anything better than
Simon Strandgaard's code.
On that same thread, GOTOU Yuuzou indicated that he wanted to add proper URL rewriting support to HEAD (1.9). It's been two years, but grep -r rewrite webrick says it hasn't happened yet.
Simon's code choked on query arguments, so I extended it as follows:
class WEBrick::HTTPServer
alias :__rewrite_old_initialize :initialize
alias :__rewrite_old_service :service
def initialize(config={}, default=WEBrick::Config::HTTP)
__rewrite_old_initialize(config, default)
@rewrite_rules = []
end
def rewrite(pattern, subst)
@logger.info("rewrite rule %s -> %s." %
[pattern.inspect, subst])
@rewrite_rules << [pattern, subst]
end
def service(req, res)
olduri = URI.parse(req.path)
olduri.query = req.query_string
old = olduri.to_s
@rewrite_rules.each do |pattern, subst|
if pattern =~ old
uri = URI.parse(old.gsub(pattern, subst))
req.instance_variable_set("@path", uri.path)
req.instance_variable_set("@query_string", uri.query)
req.instance_variable_set("@query", nil)
@logger.info("Rewrote URL %s -> %s" % [olduri.to_s, uri.to_s])
break
end
end
__rewrite_old_service(req, res)
end
end
Yes, it doesn't use define_method to redefine the instance methods while keeping the old definitions, but it doesn't matter since the above code is sitting in a 50LoC file and there's no danger of it being loaded twice.
Read more...
Read: URL rewriting with WEBrick
|
|