Skip to content

Instantly share code, notes, and snippets.

@duykhoa
Created August 27, 2016 14:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save duykhoa/643dc60ab202d21e8a20f171674de87a to your computer and use it in GitHub Desktop.
Save duykhoa/643dc60ab202d21e8a20f171674de87a to your computer and use it in GitHub Desktop.
Simple webrick server: a blog application and post repository
require 'webrick'
class BlogApplication < WEBrick::HTTPServlet::AbstractServlet
class PostRepository
Post = Struct.new(:title, :content)
def self.get
[
Post.new("post1", "content1"),
Post.new("post2", "content2")
]
end
end
def do_GET(request, response)
response.status = 200
case request.path
when "/posts"
posts = BlogApplication::PostRepository.get
response.body = render_posts(posts)
end
end
def render_posts(posts)
template = "<html><body>%s</body></html>"
yield_content = posts.map do |post|
<<-HTML
<article>
<h1>#{post.title}</h1>
<div>#{post.content}</div>
</article>
HTML
end
template % [yield_content.join]
end
end
server = WEBrick::HTTPServer.new :Port => 1234
server.mount "/", BlogApplication
trap 'INT' do server.shutdown end
server.start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment