From: Dominik Bathon Date: 2005-06-03T00:36:53+09:00 Subject: Re: TinyUrl class Hi, here is a shorter version ;-) require "net/http" require "cgi" class ShortURL def self.web(server, action, code) Net::HTTP.start(server, 80) { |http| response = http.instance_eval action response.code == code ? yield(response.read_body) : nil } end def self.rubyurl(url) web("rubyurl.com",'get("/rubyurl/create?rubyurl[website_url]='+CGI.escape(url)+'")',"302") { |body| //.match(body)[1] } end def self.tinyurl(url) web("tinyurl.com",'post("/create.php", "url='+url+'")',"200") { |body| /hidden name=tinyurl value="(.+)"/.match(body)[1] } end end Dominik On Thu, 02 Jun 2005 02:39:34 +0200, Devin Mullins wrote: > Noob, here, just playing around with Ruby (if this is spam, please let > me know). For the heck of it, I decided to refactor the duplication out > of the ShortURL class. Just to spite me, the resulting code is actually > bigger, but here you go... > > require "net/http" > require "cgi" > > class ShortURL > def self.web(server, action, code) > Net::HTTP.start(server, 80) { |http| > response = http.instance_eval action > if response.code == code > yield response.read_body > end > } > end > > def self.rubyurl(url) > ret = nil > > web("rubyurl.com",'get("/rubyurl/create?rubyurl[website_url]='+CGI.escape(url)+'")',"302") > { |body| > regex = // > ret = regex.match(body)[1] > } > ret > end > > > def self.tinyurl(url) > ret = nil > web("tinyurl.com",'post("/create.php", "url='+url+'")',"200") > { |body| > line = body.split("\n").find { |l| l =~ /hidden name=tinyurl/ } > i1 = line.index("http") > i2 = line.rindex("\"") > ret = line[i1...i2] > } > ret > end > end > > Devin