module Jok 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) end end def da topic = method_list[srand % method_list.length] joke(topic) end def method_missing(method, *args, &block) method = method.to_s super unless method_list.include? method self.class.class_eval <<-EOT, __FILE__, __LINE__ + 1 def #{method} @#{method} ||= begin joke("#{method}") end end EOT send method end def method_list @method_list ||= begin list.map do |element| element.split(" ").map(&:downcase).join("_") end.push "da" end end private def dom(method="") topic = "#{BASE_URI}/#{method.gsub("_", "-")}" response_body = HTTParty.get(topic) dom_tree = Nokogiri::HTML(response_body) return dom_tree if method == "" 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) else dom_tree end end def joke(topic="") dom(topic).xpath('//div[@class="joke3-pop-box"]/p[substring-before(@id, "_") = "joke"]').map(&:text).map(&:strip) end end end