新手问题 [已解决] Grape 的路由不能用 rake routes 显示?

chaucerling · 2015年05月20日 · 最后由 rei 回复于 2015年05月21日 · 2776 次阅读

环境:rails4.2.1, grape0.11.0

#app/api/v1/root.rb
class V1::Root < Grape::API
  version 'v1'
  format :json

  get :hello do
    {hello: "world"}
  end
end
#route.rb
mount V1::Root => "/api"

访问http://localhost:3000/api/v1/hello的结果是正确的{"hello":"world"} 但 rake routes 只能显示这样

 Prefix Verb URI Pattern Controller#Action
v1_root      /api        V1::Root

解决方案:建一个 rake task rails g test grape routes

#lib/tasks/grape.rake
namespace :grape do
  desc "TODO"
  task routes: :environment do
    V1::Root.routes.each do |route|
      path = route.route_path
      path.sub!("(.:format)",".json")
      path.sub!("/:version","")
      r = {
        method: route.route_method,
        path: path,
        params: route.route_params,
        desc: route.route_description
      }
      puts r.map{|k,v| "#{k}:#{v}"}.join('  ')
    end  
  end
end

执行 rake grape:routes 结果 method:GET path:/hello params:{} desc:

Rails 本身就能做 API,用不着 Grape。

本身不显示 你可以试试 swagger 可以根据 api 生成在线文档

额 我一般会用一个土办法,在 console 中运行

Mobile::API.routes  |r| 
  p r
 end  

用 swagger 也不错,更直观些

配合 swagger 非常方便

自建 rake task

#1 楼 @rei rubygems 那种方法吗,确实也可以

#8 楼 @chaucerling 是的,mount 个组件还要处理和框架的协作问题。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号