Created
August 27, 2016 14:23
-
-
Save duykhoa/643dc60ab202d21e8a20f171674de87a to your computer and use it in GitHub Desktop.
Simple webrick server: a blog application and post repository
This file contains 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
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