Skip to content

Instantly share code, notes, and snippets.

@jferris
Created September 13, 2013 20:31
Show Gist options
  • Select an option

  • Save jferris/6555694 to your computer and use it in GitHub Desktop.

Select an option

Save jferris/6555694 to your computer and use it in GitHub Desktop.
require 'nokogiri'
require 'net/http'
class ShakespeareAnalyzer
def initialize(url)
@url = url
end
def analyze
speech_elements.inject({}) do |result, element|
character = character_from(element)
count = count_from(element)
previous_count = result[character] || 0
result.merge(character => previous_count + count)
end
end
private
def speech_elements
document.css('SPEECH')
end
def character_from(element)
element.at('SPEAKER').text
end
def count_from(element)
element.css('LINE').length
end
def document
Nokogiri::XML.parse(xml)
end
def xml
Net::HTTP.get(host, path)
end
def host
uri.host
end
def path
uri.path
end
def uri
URI.parse(@url)
end
end
require 'rspec'
require_relative '../shakespeare_analyzer'
describe ShakespeareAnalyzer do
context '#analyze' do
it 'counts lines for each speaker' do
xml = <<-XML
<PLAY>
<SPEECH>
<SPEAKER>Macbeth</SPEAKER>
<LINE>One</LINE>
<LINE>Two</LINE>
</SPEECH>
<SPEECH>
<SPEAKER>Other Guy</SPEAKER>
<LINE>One</LINE>
<LINE>Two</LINE>
<LINE>Three</LINE>
</SPEECH>
</PLAY>
XML
analyze(xml).should eq({
'Macbeth' => 2,
'Other Guy' => 3
})
end
it 'combines counts for multiple speech blocks per speaker' do
xml = <<-XML
<PLAY>
<SPEECH>
<SPEAKER>Macbeth</SPEAKER>
<LINE>One</LINE>
<LINE>Two</LINE>
</SPEECH>
<SPEECH>
<SPEAKER>Macbeth</SPEAKER>
<LINE>Three</LINE>
</SPEECH>
</PLAY>
XML
analyze(xml).should eq({
'Macbeth' => 3
})
end
def analyze(xml)
url = 'http://example.com/somecoolxml.xml'
Net::HTTP.
stub(:get).
with('example.com', '/somecoolxml.xml').
and_return(xml)
ShakespeareAnalyzer.new(url).analyze
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment