Skip to content

Instantly share code, notes, and snippets.

@mahemoff
Created May 27, 2012 22:16
Show Gist options
  • Save mahemoff/2816140 to your computer and use it in GitHub Desktop.
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
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
> 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