tags:

views:

37

answers:

2

Hello,

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']}
      <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.

+1  A: 

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'}
Paul Rubel
This seems very nice. I will look into this further. Thank you!
Yazdaan
+1  A: 

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
clocKwize
That would be great, but unfortunately I am working with a service that has been under development on Rails for quite some time. Thank you nonetheless!
Yazdaan