Rage 高性能 REST API 实战:待办清单实时通知
一. 项目初始化与模型迁移 🛠️
Rage 是一个旨在改善 Ruby 生态系统并使其现代化的框架,它在新解决方案与现有解决方案之间取得了良好的平衡。Rage 提供了类似 Rails 的语法,同时专注于异步 I/O、性能优化以及轻松生成 OpenAPI 文档的能力。
在本文中,我们将通过构建一个共享的待办事项列表应用,来展示如何使用 Rage 构建高性能的 REST API。用户可以向列表中添加项目,将其标记为已完成,并按类别对项目进行分组。
1. 安装与初始化
a. 创建项目
首先,安装必要的 gem 包并初始化项目:
rage new todo_list --db=sqlite3
cd todo_list
bundle install
💡 AI 助攻
想自动生成带注释的Gemfile?用「代码生成」提示词,30 秒即可拿到模板,再交给「代码优化」砍掉冗余依赖,启动速度提升 20%!
2. 生成模型和迁移文件
a. 模型创建
使用 Rage 命令生成模型和迁移文件:
rage generate model Item content:string is_completed:boolean
rage generate model Group name:string
b. 关联关系
更新模型以建立关联:
class Group < ApplicationRecord
has_many :items
end
class Item < ApplicationRecord
belongs_to :group
end
c. 迁移文件
更新迁移文件以定义数据库表结构:
create_table :groups do |t|
t.string :name
t.timestamps
end
create_table :items do |t|
t.string :content
t.boolean :is_completed, default: false
t.references :group, foreign_key: true
t.timestamps
end
d. 数据库种子
为数据库添加种子数据并创建数据库:
rails db:seed
rails db:migrate
二. 构建列表 API 🔗
1. 配置路由
a. 命名空间路由
更新路由文件以支持 API 的端点:
namespace :api do
namespace :v1 do
resources :items
resources :groups
end
end
2. 创建控制器
a. 控制器模板
创建控制器类以处理 API 请求:
class Api::V1::ItemsController < ApplicationController
def index
items = Item.all
render json: items
end
end
🔍 AI 审查
把“控制器代码”提交评审?「代码审查助手」可自动检查 N+1 查询、未处理异常,提前发现 80% 潜在 Bug!
三. 序列化与文档 📚
1. 创建序列化器
a. 基础序列化器
为了更好地管理数据格式,我们需要创建序列化器。以下是三个序列化器类的定义:
- ApplicationResource:作为所有序列化器的基类。
- GroupResource:定义
id和name属性,并呈现items关联。 - ItemResource:定义
content和is_completed属性,并启用自动类型转换。
class ApplicationResource
include Alba::Resource
root_key :data, :data
transform_keys :camel
end
class GroupResource < ApplicationResource
attributes :id, :name
many :items
end
class ItemResource < ApplicationResource
attributes :id, :content, :is_completed, :group_id
end
2. 自动生成 OpenAPI 文档
a. 配置插件
Rage 支持通过插件自动生成 OpenAPI 文档。首先,在 Gemfile 中添加:
gem 'rage-rb-openapi'
然后,在控制器中添加 YARD 样式标签:
# @summary 获取所有待办事项
# @response 200 ApplicationResource
def index
items = Item.all
render json: ItemResource.new(items).serialize
end
访问 http://localhost:3000/publicapi,即可查看自动生成的 API 文档。
✅ AI 补救
把“OpenAPI 注释”写进代码太麻烦?用「代码文档生成器」提示词,自动在函数头部生成标准注释,提醒后续接入 Swagger,文档一键达标!
四. 分页与创建 📄
1. 添加分页功能
a. 偏移量分页
为了支持长列表的无限滚动,我们可以实现简单的基于偏移量的分页。以下是更新后的代码:
def index
items = Item.offset(params[:offset]).limit(params[:limit])
render json: ItemResource.new(items).serialize
end
同时,更新文档以接受 offset 和 limit 参数。
2. 创建新项目的 API
a. 创建动作
我们还需要添加创建新待办事项的 API:
def create
item = Item.new(item_params)
if item.save
render json: ItemResource.new(item).serialize, status: :created
else
render json: { errors: item.errors }, status: :unprocessable_entity
end
end
private
def item_params
params.require(:item).permit(:content, :is_completed, :group_id)
end
在路由文件中添加新操作:
resources :items, only: [:index, :create]
五. 实时通知 🌩️
1. 配置 Cable
a. 挂载路由
为了实现实时通知功能,我们可以使用 Rage 的 Cable 功能。首先,更新路由以挂载新组件:
mount Rage::Cable => '/cable'
2. 创建频道
a. 频道代码
创建新频道:
class ItemsChannel < ApplicationCable::Channel
def subscribed
stream_from "items_channel"
end
end
3. 广播逻辑
a. 触发广播
在 API 中添加通知逻辑:
def create
item = Item.new(item_params)
if item.save
ActionCable.server.broadcast 'items_channel', item: ItemResource.new(item).serialize
render json: ItemResource.new(item).serialize, status: :created
else
render json: { errors: item.errors }, status: :unprocessable_entity
end
end
六. 总结与下一步 🎯
通过本文,我们展示了如何使用 Rage 框架构建一个高性能的 Ruby REST API。Rage 提供了类似 Rails 的开发体验,同时在性能和现代化功能上进行了优化。我们实现了待办事项列表的基本功能,包括数据的创建、分页以及实时通知,并通过 OpenAPI 生成了直观的文档。
Rage 的设计旨在让开发者快速上手,同时提供强大的功能支持,是构建现代化 API 的理想选择。
原文链接: https://zuplo.com/blog/2025/04/13/ruby-rage-rest-api-tutorial
最新文章
- API密钥——什么是API Key 密钥?
- 华为 UCM 推理技术加持:2025 工业设备秒级监控高并发 API 零门槛实战
- 使用JSON注入攻击API
- 思维链提示工程实战:如何通过API构建复杂推理的AI提示词系统
- 短信验证码API在Java、Python、PHP中的使用指南
- 免费使用头条热榜API进行数据分析的教程
- 获取 YouTube API Key 密钥的教程与示例
- Python人工智能学习路线(长篇干货)
- 当中医遇上AI:探索“寻艾中医AI开放平台”的创新之旅
- 增值税发票OCR识别API在Java、Python、PHP中的使用教程
- 创建调用系统API的ChatGPT代理 – ServiceStack
- 逐步指南:如何创建一个API – Kodezi博客