The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
URL rewriting with WEBrick

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
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
Reply to this message Reply

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

Advertisement

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)  # so it gets reparsed
        @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*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.


Read more...

Read: URL rewriting with WEBrick

Topic: Debugging Ruby On Rails Applications with LightTPD and Cylon Previous Topic   Next Topic Topic: Rose's First irb Session

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use