Ruby

You need Ruby 3.1 or later. The runtime comatype (packages/ruby) works with the standard library only (json, net/http, bigdecimal, socket and so on). Ruby is a dynamic language, so the generated code writes out a "description of the types", and the runtime does conversion and validation.

What is generated#

comatype_gen/
├─ types.rb                 Named types (subclasses of Comatype::Model / Comatype::Enum)  ComatypeGen::Types
├─ init.rb                  Wrappers, ctx and wrapper statuses                            ComatypeGen::Init
├─ user_put_id.rb           One per endpoint                                              ComatypeGen::UserPutId
└─ all.rb                   Requires everything

Load it with require_relative "comatype_gen/all".

Client#

user_put_id.rb
require "comatype"
require_relative "comatype_gen/all"

UserPutId = ComatypeGen::UserPutId

def put_user(id, user)
  # Arguments are params: search: headers: body: (a Model, or a hash keyed by attr). Types are validated from params / body of put__id.comat
  res = Comatype::C.put(UserPutId::ENDPOINT, params: { id: id }, body: user)

  case res
  when UserPutId::S200 then res.body # UserData (res.headers is S200Headers)
  when UserPutId::S404 then res.body # ApiError
  end
end
  • The arguments are params: search: headers: body: (a Model instance, or a hash keyed by attribute names). Leave them out if there are none.
  • The return value is an instance of S200 S404 ... (res.status res.body res.headers). Narrow it with case / when.
  • A status that is not in the .comat is Comatype::UnexpectedStatusError, and a validation error is Comatype::ValidationError (path and reason).
  • Communication uses Net::HTTP (synchronous).
init.rb
# Client init file: pass the implemented wrappers
# The base url defaults to baseUrl in init.comat. Override with the COMATYPE_BASE_URL environment variable or base_url:
# Call init_comatype once at startup (whether a wrapper is on or off is decided by defaults.comat and `wrap` in each .comat)
require "comatype"
require_relative "comatype_gen/all"
require_relative "wrappers/auth"

def init_comatype
  Comatype::C.init(
    # With the generated Init.wrappers, a missing wrapper declared in init.comat raises ArgumentError
    wrappers: ComatypeGen::Init.wrappers(auth: AUTH),
    # Used by `cookie on` endpoints. The cookie jar keeps the httpOnly cookie
    cookies: true
  )
end
wrappers/auth.rb
# A wrapper is implemented as a lambda taking (req, nxt) (corresponds to the `wrapper auth` of init.comat)
AUTH = lambda do |req, nxt|
  req.headers["Authorization"] = "Bearer #{ENV['API_TOKEN']}"
  nxt.call(req)
end

Server#

user_put_id.rb
require "comatype"
require_relative "comatype_gen/all"

UserPutId = ComatypeGen::UserPutId

def register_user_put_id(server)
  server.put(UserPutId::ENDPOINT) do |req|
    # req.params.id: String, req.body: UserData, req.ctx[:auth].user (wrap auth is on)
    user = Db::User.update(req.params.id, req.body) # the app's own storage
    next UserPutId::S404.new(ComatypeGen::Types::ApiError.new(code: "not_found", message: "user not found")) unless user

    # headerRes (X-Resource-Version) of user/defaults.comat
    UserPutId::S200.new(user, headers: { x_resource_version: "v2" })
  end
end
  • Register handlers as blocks on an instance of Comatype::S. The return value is a response such as S200.new(body, headers: {...}). Cookies use .with_cookie(value, max_age: 3600) / .clear_cookie.
  • s is Rack compatible (run s). s.handle(method, target, headers, body) is the entry point for any framework, and s.serve(port: 3000) is a simple server built on the standard library only.
init.rb
# Server init file: pass the implemented wrappers. The cookie settings (name, httpOnly, etc.) are in init.comat
require "comatype"
require_relative "comatype_gen/all"
require_relative "wrappers/auth"

def init_comatype(server)
  # With the generated Init.wrappers, a missing wrapper declared in init.comat raises ArgumentError
  server.init(ComatypeGen::Init.wrappers(auth: AUTH))
end
wrappers/auth.rb
# A wrapper is implemented as a lambda taking (req, nxt) (corresponds to the `wrapper auth` of init.comat)
require_relative "../comatype_gen/all"

AUTH = lambda do |req, nxt|
  user = verify_session(req.cookie("session")) # the app's own logic
  next ComatypeGen::Init.s401(ComatypeGen::Types::ApiError.new(code: "unauthorized", message: "login required")) unless user

  # On endpoints with `wrap auth` on, a handler can read req.ctx[:auth].user
  req.ctx[:auth] = ComatypeGen::Init::AuthCtx.new(user: user)
  nxt.call(req)
end

Type mapping#

  • string bool int are String true/false Integer. int64 is Integer (a string on the wire).
  • date is Date, datetime is Time, decimal is BigDecimal, url is URI, bytes is String (binary), and json is Hash / Array.
  • The uuid family, email, phone and time are Strings with a validated format (uuids are normalized to lower case).
  • Optional (?) and T | null can be nil. Attribute names are snake_case (X-Request-Id → x_request_id).
  • Constraints (min max pattern) are checked by the runtime when reading and when sending.