【问题标题】:How to get routes by Grape API如何通过 Grape API 获取路由
【发布时间】:2017-11-23 05:21:26
【问题描述】:

我使用 gem,grape 作为 api。 我尝试通过命令rake grape:routes获取api url

    namespace :grape do
      desc "routes"
      task :routes => :environment do
        API::Root.routes.map { |route| puts "#{route} \n" }
      end
    end

但我得到了rake grape:routes

    #<Grape::Router::Route:0x007f9040d13878>
    #<Grape::Router::Route:0x007f9040d13878>
    #<Grape::Router::Route:0x007f9040d13878>
    #<Grape::Router::Route:0x007f9040d13878>
    ...

我想要这样的东西。

    version=v1, method=GET, path=/services(.:format)
    version=v1, method=GET, path=/services/:id(.:format)
    ...

我的葡萄实现如下。这很好用。

    module API
      class Root < Grape::API
        version 'v1', using: :path
        format :json

        helpers Devise::Controllers::Helpers

        mount API::Admin::Services
      end
    end



    module API
      class Services < Grape::API
        resources :services do
          resource ':service_id' do
            ...
          end
        end
      end
    end

【问题讨论】:

    标签: ruby-on-rails api grape


    【解决方案1】:

    尝试将以下内容添加到您的 Rakefile 中,如 proposal

    中所述
    desc "Print out routes"
    task :routes => :environment do
      API::Root.routes.each do |route|
        info = route.instance_variable_get :@options
        description = "%-40s..." % info[:description][0..39]
        method = "%-7s" % info[:method]
        puts "#{description}  #{method}#{info[:path]}"
      end
    end
    

    或者

    试试下面提到的here

    desc "API Routes"
    task :routes do
      API::Root.routes.each do |api|
        method = api.request_method.ljust(10)
        path = api.path
        puts "#{method} #{path}"
      end
    end
    

    然后运行rake routes

    还有一些为此目的而构建的宝石(grape_on_rails_routes & grape-raketasks)。您可能有兴趣看看它们。

    【讨论】:

      猜你喜欢
      • 2016-11-16
      • 2012-12-25
      • 2017-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-30
      • 2018-04-04
      • 2019-02-10
      相关资源
      最近更新 更多