Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- require 'open-uri'
- require 'nokogiri'
- require 'cgi'
- module QDB
- class Base
- attr_accessor :id
- attr_reader :lines
- attr_reader :url
- def initialize id = nil, lines = 4
- @id = id
- @lines = lines
- if !@id.nil?
- @id = retrieve_latest_quote_id if @id.to_sym === :latest
- self.retrieve_quote
- self.retrieve_meta
- end
- end
- def retrieve_latest_quote_id
- raise "retrieve_latest_quote_id must be overridden."
- end
- def retrieve_quote params={}
- raise "retrieve_quote must be overridden."
- end
- def retrieve_meta params={}
- raise "retrieve_meta must be overridden."
- end
- def format lines = 4
- {
- :id => @id,
- :quote => self.retrieve_quote(:id => @id, :lines => lines),
- :meta => self.retrieve_meta(:id => @id),
- :lines => @lines,
- :url => @url,
- }
- end
- end
- class Bash < Base
- @@_base_url = "http://bash.org/"
- def retrieve_latest_quote_id
- url = "#{@@_base_url}?latest"
- o = Nokogiri::HTML(open(url));
- id = CGI.unescape_html o.at(".quote a b").children.to_s.strip.gsub("\r","").gsub("#","")
- id.to_i
- end
- def retrieve_quote params={}
- id = params[:id]||:latest;
- lines = params[:lines]||4;
- @url = "#{@@_base_url}?#{id}"
- o = Nokogiri::HTML(open(@url))
- quotes = CGI.unescape_html o.at(".qt").children.to_s.gsub(/[\r\n]/,"")
- quotes = quotes.split(/<br *\/?>/i)
- @lines = quotes.size
- quotes[0..lines-1]
- end
- def retrieve_meta params={}
- id = params[:id]||:latest;
- @url = "#{@@_base_url}?#{id}"
- o = Nokogiri::HTML(open(@url))
- rating = o.at(".quote").children.to_s.match(/\((-?\d+)\)/)[1]
- "Rating: #{rating}"
- end
- end
- end
- ## Begin testing.
- bash = QDB::Bash.new
- bash.id = 61129
- format_hash = bash.format
- output = []
- output << "Bash quote ##{format_hash[:id]} (#{format_hash[:meta]}):"
- output << format_hash[:quote]
- footer = ["View"]
- footer << (format_hash[:lines] > format_hash[:quote].size ? "more from" : nil)
- footer << "this quote at #{format_hash[:url]}."
- output << footer.reject(&:nil?).join(" ")
- output.reject(&:nil?).join("\n");
- puts output;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement