Skip to content

Instantly share code, notes, and snippets.

@mariozig
Last active October 10, 2015 16:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mariozig/82dab7bad941d301622d to your computer and use it in GitHub Desktop.
Save mariozig/82dab7bad941d301622d to your computer and use it in GitHub Desktop.
require "http/client"
class Word
def initialize(word)
raise ArgumentError.new "Not a single word" if word.split(" ").size > 1
@word = word
end
def wiki_title
wiki_page = WikipediaPage.new(@word)
wiki_page.title
end
end
class WikipediaPage
def initialize(string)
@string = string
end
def page
@page ||= fetch
end
def title
wikipedia_title_matcher = /<title[^>]*>(.*?) - Wikipedia, the free encyclopedia<\/title>/
page.match(wikipedia_title_matcher) { |md| md[1] }
end
private def fetch
url = "https://en.wikipedia.org/wiki/#{@string.capitalize}"
response = HTTP::Client.get(url)
response.body.lines.to_s
end
end
##############
# RUNNER #
##############
# Happy path
word = Word.new "tomato"
puts word.wiki_title
# Sad path
two_words = Word.new "so sorry"
##############
# OUTPUT #
##############
# $ crystal run person.cr
# Tomato
# Not a single word (ArgumentError)
# [4502914194] *CallStack::unwind:Array(Pointer(Void)) +82
# [4502914097] *CallStack#initialize<CallStack>:Array(Pointer(Void)) +17
# [4502914056] *CallStack::new:CallStack +40
# [4502916609] *Exception@Exception#initialize<ArgumentError, String>:CallStack +33
# [4502916541] *ArgumentError#initialize<ArgumentError, String>:CallStack +29
# [4502916476] *ArgumentError::new<String>:ArgumentError +92
# [4502966288] *Word#initialize<Word, String>:String +64
# [4502966188] *Word::new<String>:Word +76
# [4502873457] __crystal_main +24097
# [4502881488] main +32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment