open-uriを無理やりPOST対応にする

open-uri便利なんですがPOSTには対応してないんですよね。
[ruby-dev:19033]あたりで少し議論されてるっぽいですが、その後さっぱり。
他のMethodも考えると問題が難しくなるので、POSTにのみ限ってopen-uriに細工をしてみた。


[]$ diff -U2 open-uri.rb.orig open-uri.rb[]
[]--- open-uri.rb.orig 2006-08-05 03:05:40.000000000 +0900[]
[]+++ open-uri.rb 2006-11-29 22:29:12.406250000 +0900[]
[]@@ -91,4 +91,5 @@[]
[] module OpenURI[]
[] Options = {[]
[]+ :post => nil,[]
[] :proxy => true,[]
[] :proxy_http_basic_authentication => true,[]
[]@@ -299,10 +300,14 @@[]
[] sock.post_connection_check(target_host)[]
[] end[]
[]- req = Net::HTTP::Get.new(request_uri, header)[]
[]+ if options[:post][]
[]+ req = Net::HTTP::Post.new(request_uri, header)[]
[]+ else[]
[]+ req = Net::HTTP::Get.new(request_uri, header)[]
[]+ end[]
[] if options.include? :http_basic_authentication[]
[] user, pass = options[:http_basic_authentication][]
[] req.basic_auth user, pass[]
[] end[]
[]- http.request(req) {|response|[]
[]+ http.request(req,options[:post]) {|response|[]
[] resp = response[]
[] if options[:content_length_proc] && Net::HTTPSuccess === resp[]
*1

open("hogehoge.cgi",:post=>"id=foo&pass=bar")
な感じでゲッツ。じゃなくてポストできるようになる。

    • -

追記:1.8系だとssl関係のオプションがなくてうまくパッチが当たらなかったたため、:postの入れる位置を前の方に変更しました。後、これは整合性とか美しさはともかくPOSTを使いたいっていう欲求から出てきたもののため、これ以上手は入れないと思います。。。