lib/xkcd.rb in xkcd-0.0.7 vs lib/xkcd.rb in xkcd-0.0.8

- old
+ new

@@ -1,10 +1,8 @@ -#!/usr/bin/env ruby -require 'nokogiri' +#!/usr/bin/evn ruby +require 'net/http' require 'open-uri' -require 'json' - # The main XKCD driver class XKCD # Get img/comic URL from xkcd # # Example: @@ -12,29 +10,23 @@ # => "http://imgs.xkcd.com/comics/hell.png" # # >> XKCD.comic # => "http://xkcd.com/891/" - def self.comic - open('http://dynamic.xkcd.com/random/comic/').base_uri.to_s + def self.comic() + # This method gets random comic links from xkcd, the uri is the redirected location found in the resp headers + uri = URI.parse 'http://dynamic.xkcd.com/random/comic/' + req = Net::HTTP::Get.new(uri.request_uri) + http = Net::HTTP.new(uri.host) + res = http.start { |server| + server.request(req) + } + res["location"] end - class << XKCD - alias_method :get, :comic - end - -=begin def self.img - img = Nokogiri::HTML(open('http://dynamic.xkcd.com/random/comic/')).css('#comic img')[0] - img_url = img.attributes["src"].value - img_title = img.attributes["title"].value - "#{img_title} : #{img_url}" - end -=end - def self.img - max = JSON.parse(open('http://xkcd.com/info.0.json').read)["num"] - comic_num = Random.rand(max) - comic_num = 1 if comic_num == 404 # Avoid 404th comic ;) - comic = JSON.parse(open("http://xkcd.com/#{random_comic}/info.0.json").read) - "#{comic['alt']} : #{comic['img']}" + url = 'http://dynamic.xkcd.com/random/comic/' + html = open(url).read() + imgs = URI.extract(html).select{ |l| l[/comics\//]} + imgs.first end end