You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何借助parser工具为Rails 6容器动态添加健康检查路由?

为Rails 6容器自动添加健康检查路由方案

核心思路

通过parser gem解析config/routes.rb的抽象语法树(AST),精准找到Rails.application.routes.draw do ... end代码块,在内部插入健康检查路由,避免直接追加导致的语法错误,同时集成到Docker构建流程实现动态修改。


步骤1:编写路由修改脚本

创建script/add_health_check_route.rb脚本,负责解析、检查、插入路由:

require 'parser/current'
require 'unparser'

# 读取路由文件
routes_path = 'config/routes.rb'
content = File.read(routes_path)
ast = Parser::CurrentRuby.parse(content)

health_route_exists = false

# 遍历AST定位routes.draw块
ast.children.each do |node|
  next unless node.is_a?(Parser::AST::Node) && node.type == :send
  next unless node.children[1] == :draw && node.children[0].children.include?(:routes)

  draw_block = node.children[2]
  next unless draw_block.type == :block

  # 检查是否已存在健康检查路由
  draw_block.children[1].children.each do |route_node|
    next unless route_node.type == :send && route_node.children[1] == :get
    path_node = route_node.children[2]
    if path_node.type == :str && path_node.children[0] == '/health_check'
      health_route_exists = true
      break
    end
  end

  # 插入新路由到块开头(避免被其他路由规则覆盖)
  unless health_route_exists
    health_route_ast = Parser::CurrentRuby.parse("get '/health_check', to: 'health_check#show'").children.first
    draw_block.children[1].children.unshift(health_route_ast)
  end
end

# 写入修改后的内容
unless health_route_exists
  modified_content = Unparser.unparse(ast)
  File.write(routes_path, modified_content)
end

步骤2:集成到Docker构建流程

修改Dockerfile,在构建阶段执行脚本并生成对应控制器:

FROM ruby:2.7-slim

# 安装系统依赖
RUN apt-get update && apt-get install -y --no-install-recommends \
    build-essential nodejs git

WORKDIR /app

# 复制Gemfile并安装依赖
COPY Gemfile Gemfile.lock ./
RUN bundle config set without 'development test' && bundle install

# 临时安装parser(无需写入Gemfile)
RUN gem install parser unparser

# 复制项目文件
COPY . .

# 生成health_check控制器(跳过自动生成的路由)
RUN rails generate controller health_check show \
    --skip-assets --skip-helper --skip-template-engine --skip-route

# 执行路由修改脚本
RUN ruby script/add_health_check_route.rb

# 生产环境预编译资产
RUN RAILS_ENV=production bundle exec rails assets:precompile

CMD ["bundle", "exec", "puma", "-C", "config/puma.rb"]

关键注意事项

  • 使用unparser生成代码,保证修改后路由文件的格式与原文件一致,避免手动拼接字符串的格式问题
  • 脚本内置重复检查,多次运行也不会重复添加路由
  • 生成控制器时添加--skip-route参数,避免Rails自动生成多余路由规则

内容的提问来源于stack exchange,提问作者caduceus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 22:21:02