开发者

Ruby URI Manipulation

Is there any way to manipulate a URI in Ruby to accept parameters without the use of ? and &?

For example, I wish to do the following:

http://localhost:5000/service/get/ip/port

instead of

http://localhost:5000/service?ip=192.168.1.1&port=1

To return information for a given device. This would utilizes a fully REST-based interface.

example code:

hello_proc = lambda do |req,res|
  res['Content-Type'] = "text/html"
  res.body = %{
     <html><body>
      Hello. You are calling from a #{req['User-Agent']}
开发者_Go百科      <p>
      I see parameters: #{req.query.keys.join(', ')}
     </body></html>
  }
end

Using this URL: http://localhost:5000/a/b In the above, req's output for a given URL would be:

GET /a/b HTTP/1.1

Within 'req', how may one go about handling the URI?

Thank you in advance.


Routing is what you're looking for. From the docs for routing at api.rubyonrails.org

Routes can generate pretty URLs. For example:

map.connect 'articles/:year/:month/:day',
            :controller => 'articles',
            :action     => 'find_by_date',
            :year       => /\d{4}/,
            :month      => /\d{1,2}/,
            :day        => /\d{1,2}/

Changing this up a bit you're all set for ips and ports.

Using the route above, the URL "localhost:3000/articles/2005/11/06" maps to

params = {:year => '2005', :month => '11', :day => '06'}


You should try sinatra, it's a very lightweight REST focused layer on top of rack, with it you could do:

get '/service/get/:ip/:port' do |ip, port|
  content_type "text/html"

  "IP: #{ip} PORT: #{port}"
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜