lib/jok/joke_factory.rb in jok-0.0.4 vs lib/jok/joke_factory.rb in jok-0.0.5

- old
+ new

@@ -2,11 +2,11 @@ class JokeFactory BASE_URI = "http://www.laughfactory.com/jokes/".freeze def list @list ||= begin - dom.xpath('//div[@class="left-nav"]/ul/li/a').map(&:text) + Nokogiri::HTML(HTTParty.get(BASE_URI)).xpath('//div[@class="left-nav"]/ul/li/a').map(&:text) end end def da topic = method_list[srand % method_list.length] @@ -36,29 +36,35 @@ end end private - def dom(method="") - topic = "#{BASE_URI}/#{method.gsub("_", "-")}" + # Cautious: Randomness!!! + def parse_uri(method="") + topic = "#{BASE_URI}#{method.gsub("_", "-")}" response_body = HTTParty.get(topic) - dom_tree = Nokogiri::HTML(response_body) - return dom_tree if method == "" + return topic if method == "" + dom_tree = Nokogiri::HTML(response_body) + pagination_items = dom_tree.xpath('//div[@class="pagination"]/ul/li').map(&:text).map(&:strip) if pagination_items.length > 0 selected_item = pagination_items[srand % (pagination_items.length - 1)] - - response_body = HTTParty::get("#{topic}/#{selected_item}") - Nokogiri::HTML(response_body) + "#{topic}/#{selected_item}" else - dom_tree + topic end end def joke(topic="") - dom(topic).xpath('//div[@class="joke3-pop-box"]/p[substring-before(@id, "_") = "joke"]').map(&:text).map(&:strip) + uri = parse_uri(topic) + response_body = HTTParty.get(uri) + dom = Nokogiri::HTML(response_body).xpath('//div[@class="joke3-pop-box"]/p[substring-before(@id, "_") = "joke"]') + + dom.map do |child| + OpenStruct.new(content: child.text.strip, link: "#{uri}##{child.attributes["id"].value}") + end end end end