WEBrick server

Serve a directory

WEBrick is a bundled gem: a full Ruby install has it, and a minimal one runs gem install webrick first. It serves static files with two lines of code. Point DocumentRoot at a folder and start the server.

Open the shown port in a browser to browse the folder content during local development.

require "webrick" server = WEBrick::HTTPServer.new(Port: 8000, DocumentRoot: ".") server.start

Mount a proc

Dynamic paths need code, not files. Mount a path with a block that receives the request and builds the response.

The block runs on every visit, so the response can depend on query params, headers, and time of day.

require "webrick" server = WEBrick::HTTPServer.new(Port: 8000) server.mount_proc("/hello") do |_req, res| res.body = "hi" end server.start

curl http://localhost:8000/hello

hi

Serve JSON

Small APIs return JSON instead of HTML pages. Set the content type header and dump a Ruby structure with JSON generate.

Clients parse the body back into arrays and hashes, exactly as the JSON lesson describes.

require "webrick" require "json" server = WEBrick::HTTPServer.new(Port: 8000) server.mount_proc("/todos") do |_req, res| res["Content-Type"] = "application/json" res.body = JSON.generate([{ title: "write tests" }]) end server.start

Trap INT to stop

A server started from the terminal owns that terminal until it stops. Trap the interrupt signal so Control plus C shuts it down cleanly.

Without the trap the process may need a forced kill, which can leave the port busy for a while.

require "webrick" server = WEBrick::HTTPServer.new(Port: 8000) trap("INT") { server.shutdown } server.start

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does this program print? require "json" res = {} res["Content-Type"] = "application/json" res["body"] = JSON.generate([{ title: "write tests" }]) puts res["Content-Type"] puts res["body"]

    Answer

    application/json / [{"title":"write tests"}]

    The handler sets the content type and writes the generated JSON into the body, and generate writes compact JSON.

  2. What does this program print? require "webrick" server = WEBrick::HTTPServer.new(Port: 8000) puts server.config[:Port]

    Answer

    8000

    The options hash is kept in config, and the port asked for is the value stored there.

  3. What does server.mount_proc("/hello") do |req, res| ... end do?

    Answer

    Registers a block that runs on every request to /hello

    The block is the handler, and it runs for each request that matches the mounted path.

  4. What does the DocumentRoot option tell WEBrick?

    Answer

    Which folder holds the static files to serve

    The document root is the folder a static request is resolved against.

  5. What does this program print? require "json" body = '[{"title": "write tests"}]' puts JSON.parse(body).first["title"]

    Answer

    write tests

    The JSON array becomes an array of hashes with string keys, and first reads the only element.

  6. What does this program print? trap("INT") { puts "trapped" } Process.kill("INT", Process.pid) sleep 0.1

    Answer

    trapped

    The trap replaces the default action, so the handler runs when the signal arrives.

  7. Why does the page trap INT before server.start?

    Answer

    To stop the server cleanly when Control and C are pressed

    A trapped interrupt calls shutdown, so the port is released instead of needing a forced kill.

  8. What does server.start do?

    Answer

    Runs the request loop until the server is shut down

    start enters the accept loop, which is why the page says the server owns the terminal until it stops.

  9. Which line makes a JSON handler answer with the right content type?

    Answer

    res["Content-Type"] = "application/json"

    The response object holds the headers that are sent back, and the content type belongs there.

  10. Why does WEBrick need gem install webrick on a minimal Ruby 3.4?

    Answer

    It is a bundled gem rather than a default gem, so a minimal install does not carry it

    A full install includes the bundled gems; a minimal one does not, and the require fails until the gem is added.

Article author: Arthur Isaev