class RandomShakespeare::Parser

Public Class Methods

new(filename) click to toggle source
# File lib/random_shakespeare/parser.rb, line 6
def initialize(filename)
  file = get_file(filename)
  @doc = Nokogiri::XML(file)
end

Public Instance Methods

all_lines() click to toggle source
# File lib/random_shakespeare/parser.rb, line 11
def all_lines
  return @all_lines if doc_parsed?
  @all_lines = parse_doc
end
lines_by_speaker(speaker) click to toggle source
# File lib/random_shakespeare/parser.rb, line 20
def lines_by_speaker(speaker)
  all_lines[speaker.titleize]
end
speakers() click to toggle source
# File lib/random_shakespeare/parser.rb, line 24
def speakers
  all_lines.keys
end
total_lines() click to toggle source
# File lib/random_shakespeare/parser.rb, line 16
def total_lines
  all_lines.values.flatten.count
end

Private Instance Methods

doc_parsed?() click to toggle source
# File lib/random_shakespeare/parser.rb, line 39
def doc_parsed?
  !@all_lines.nil? && !@all_lines.empty?
end
get_file(filename) click to toggle source
# File lib/random_shakespeare/parser.rb, line 30
def get_file(filename)
  filename = File.join(File.expand_path('.'), filename)
  if File.exist? (filename)
    File.open(filename, &:read)
  else
    Downloader.new.file
  end
end
parse_doc() click to toggle source
# File lib/random_shakespeare/parser.rb, line 43
def parse_doc
  ret = {}
  @doc.xpath('//SPEECH').each do |speech_doc|
    parse_speech_doc(ret, speech_doc)
  end
  ret
end
parse_speech_doc(ret, speech_doc) click to toggle source
# File lib/random_shakespeare/parser.rb, line 51
def parse_speech_doc(ret, speech_doc)
  speaker = speech_doc.xpath('SPEAKER').text.titleize
  ret[speaker] ||= []
  lines = speech_doc.xpath('LINE').map(&:text)
  ret[speaker] << lines.join("\n")
end