Posted By

felipec on 04/15/07


Tagged

web20 rest


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

maxkks
nog
sergeizen
webstic


Ruby REST


 / Published in: Ruby
 

Very basic but functional REST helper.

  1. require 'net/https'
  2.  
  3. module REST
  4. class Connection
  5. def initialize(base_url, args = {})
  6. @base_url = base_url
  7. @username = args[:username]
  8. @password = args[:password]
  9. end
  10.  
  11. def request_get(resource, args = nil)
  12. request(resource, "get", args)
  13. end
  14.  
  15. def request_post(resource, args = nil)
  16. request(resource, "post", args)
  17. end
  18.  
  19. def request(resource, method = "get", args = nil)
  20. url = URI.join(@base_url, resource)
  21.  
  22. if args
  23. # TODO: What about keys without value?
  24. url.query = args.map { |k,v| "%s=%s" % [URI.encode(k), URI.encode(v)] }.join("&")
  25. end
  26.  
  27. case method
  28. when "get"
  29. req = Net::HTTP::Get.new(url.request_uri)
  30. when "post"
  31. req = Net::HTTP::Post.new(url.request_uri)
  32. end
  33.  
  34. if @username and @password
  35. req.basic_auth(@username, @password)
  36. end
  37.  
  38. http = Net::HTTP.new(url.host, url.port)
  39. http.use_ssl = (url.port == 443)
  40.  
  41. res = http.start() { |conn| conn.request(req) }
  42. res.body
  43. end
  44. end
  45. end

Report this snippet  

You need to login to post a comment.