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::HTTPServeralias:__rewrite_old_initialize:initializealias:__rewrite_old_service:servicedef initialize(config={},default=WEBrick::Config::HTTP)__rewrite_old_initialize(config,default)@rewrite_rules=[]enddef rewrite(pattern,subst)@logger.info("rewrite rule %s -> %s."%[pattern.inspect,subst])@rewrite_rules<<[pattern,subst]enddef service(req,res)olduri=URI.parse(req.path)olduri.query=req.query_stringold=olduri.to_s@rewrite_rules.eachdo|pattern,subst|ifpattern=~olduri=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)# so it gets reparsed@logger.info("Rewrote URL %s -> %s"%[olduri.to_s,uri.to_s])breakendend__rewrite_old_service(req,res)endend
Yes, it doesn't use define_method to redefine the instance methods while keeping the old definitions*1, 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.