Created
May 27, 2012 22:16
-
-
Save mahemoff/2816140 to your computer and use it in GitHub Desktop.
A simple HTTP-like document, with some headers on top and a body
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Document | |
attr_accessor :body, :headers | |
def initialize(text) | |
matches = text.match /^(?:([\s\S]+)\n\s*\n)?([\s\S]+)$/ | |
self.body = matches[2] | |
self.headers = {} | |
headers_text = matches[1] || '' | |
headers_text.split(/\n/).map { |header_text| | |
if matches = header_text.match(/(.+): (.+)/) | |
self.headers[matches[1]] = matches[2] | |
end | |
} | |
end | |
def header(key) | |
self.headers[key] | |
end | |
def to_s | |
self.headers.inspect + "\n" + self.body.inspect | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
> doc = Document.new "name: Mario\nborn: 1981\nnemesis: Donkey Kong\n\nMario is a pretty fearless dude." | |
=> {"name"=>"Mario", "born"=>"1981", "nemesis"=>"Donkey Kong"} | |
... | |
"Mario is a pretty fearless dude." | |
> doc.header 'nemesis' | |
=> "Donkey Kong" | |
> doc.body | |
=> "Mario is a pretty fearless dude." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment