Runcobo 是我在做的一个 Crystal Web 框架,最近发布了 3.1.5。
Runcobo 的写法参考了 Rails,路由、请求参数和模板在编译时检查,SQL 在生成代码时检查。
我在做一个社交 App,后端用 Rails 写的。考虑到后面对 CPU、内存等性能的要求会比较高,需要提前做准备。
常见的做法是换成 Go 或 Rust 重写,前阵子 Ruby China 上也在讨论 DHH 用 AI 在多种语言上重写 Campfire。但我写了很多年 Ruby,还是想用接近 Ruby 的方式写代码。
这时候想起了 6 年前写的 Runcobo。2020 年我在 Ruby China 发过它的 1.0 版本,当时只是一个极简的 API 框架。Crystal 的语法和 Ruby 很像,又能编译成原生二进制运行,正好合适。
不过 1.0 的功能撑不起实际项目,于是把它拿出来重构:参数校验、ORM、数据库迁移、命令行工具、实时推送,一项项补上。希望写 Rails 的人能用熟悉的方式写 Crystal。
一个接口对应一个 action 类,路由写在类里,同目录下放参数契约(contract)和模板:
# src/actions/posts/create_post.cr
class Posts::CreatePost < Blog::AdminAction
post "/posts"
call do
input = validate(CreatePostContract)
post = store.create_post(title: input.title.strip, body: input.body)
render status_code: 201 # 渲染 create_post.jbuilder
end
end
# src/actions/posts/create_post_contract.cr
class Posts::CreatePostContract < RequestValidation::Contract
schema do
required :title, String, filled: true, strip: true, max_size: 200
required :body, String, filled: true, max_size: 20_000
end
end
# src/actions/posts/create_post.jbuilder
json.partial! "posts/partials/post", post: post
validate 之后,input.title 的类型是 String。参数不合法时返回 422,列出所有错误,call 里后面的代码不会执行:
{
"errors": [
{"source": "request", "path": ["title"], "code": "filled", "params": {}},
{"source": "request", "path": ["body"], "code": "missing", "params": {}}
]
}
数据库访问写 SQL:
-- db/queries/posts.sql
-- name: CreatePost :one
INSERT INTO posts (title, body) VALUES (sqlc.arg(title), sqlc.arg(body))
RETURNING id, title, body, created_at, updated_at;
bin/cobo generate 根据迁移文件把它生成为 store.create_post(title: String, body: String),返回值的 created_at 是 Time。
routes.rb → 一个接口一个 action 类,路由写在类里validate
before_action / skip_before_action / after_action → before / skip / after
ApplicationController → Blog::BaseAction
store 方法(基于 sqlc)includes(:comments) → WHERE post_id = ANY(...) 批量查询 + group_by
db/migrate/*.rb → SQL 迁移文件(dbmate)rails s / rails c / rails routes → bin/cobo dev / bin/cobo console / bin/cobo routes
rails db:migrate → bin/cobo db migrate
ws 路由和 stream 推送详细对照见 Coming from Rails。
✅ 内置
cobo routes 列出所有路由null
before / after / skip,可继承cobo db 命令管理,基于 dbmatecobo dev 保存后自动编译重启,编译失败时继续运行旧版本runcobo/testing 启动真实服务器,测试 SSE 和 WebSocket🔌 外部库
✍️ 自行实现
before 过滤器里校验 Token 或 Cookiepublic/
需要 Crystal 1.22 以上。用数据库的话,还需要 sqlc 1.31.1,以及 PostgreSQL 或 MySQL 服务器;SQLite 不需要服务器。
crystal init app blog
cd blog
shard.yml 加上依赖:
dependencies:
runcobo:
github: runcobo/runcobo
version: ~> 3.1
shards install # 同时编译出 bin/cobo
bin/cobo init # 默认 PostgreSQL,可选 --database sqlite / mysql / none
bin/cobo dev
打开 http://localhost:3000 会看到欢迎页:

examples/blog 是一个博客:
JOIN 统计,评论用一条批量查询加载;配套教程:https://runcobo.github.io/runcobo/guide/example
有问题或建议,欢迎在 GitHub Issues 或这里留言。