17 June 2023

Ruby - Creating a basic Rack server

Sometimes it’s just easier to create a base RACK app so you can handle basic requests so you can write some Ruby and make a simple API.

The application

A response class

# api_response.rb

class ApiResponse
  def call(env)
    req = Rack::Request.new(env)
    server = env['REQUEST_URI'].delete('/').to_i
    if ($result[server] != nil)
      [200, {"Content-Type" => "application/json"}, [$result[server].to_json]]
    else
      [404, {"Content-Type" => "application/json"}, [{error: 'Invalid Server Number'}.to_json]]
    end
  end
end

You can get the path info by doing something like

case req.path_info
    when /hello/

The config file

Create a config.ru file

# config.ru
require './api_response.rb'

run ApiResponse.new

Run the application

rackup
tags: ruby - rack