32
30

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Rails] Grapeのroutesを参照する

Posted at

RailsでAPIを開発する時大活躍のgrape

しかし、grapeで作成したrouteはrake routesには反映されないのでちょっと困る。

そんな時は、

AppName::API.routes

でアクセス可能です。

例えば、ルーティングが以下のような構造の時は、

api/sample_app/api.rb
    resource :conversions do
      post :create do
        # create conversion
      end
      post :update do
        # update conversion
      end
    end

AppName::API.routesで以下を取得できます。

[2] pry(main)> SampleApp::API.routes
=> [#<Grape::Route:0x007fd0ca428e50
  @options=
   {:prefix=>nil,
    :version=>"v1",
    :namespace=>"/conversions",
    :method=>"POST",
    :path=>"/conversions/create(.:format)",
    :params=>{},
    :compiled=>/\A\/conversions\/create(?:\.(?<format>[^\/.?]+))?\Z/}>,
 #<Grape::Route:0x007fd0cb11aaa0
  @options=
   {:prefix=>nil,
    :version=>"v1",
    :namespace=>"/conversions",
    :method=>"POST",
    :path=>"/conversions/update(.:format)",
    :params=>{},
    :compiled=>/\A\/conversions\/update(?:\.(?<format>[^\/.?]+))?\Z/}>]

pathだけ抜き出したい時は

[3] pry(main)> SampleApp::API.routes.each { |route| p route.instance_variable_get(:@options)[:path] }
"/conversions/create(.:format)"
"/conversions/update(.:format)"

こんな感じ。

cf

grape自体については、公式以外では以下が参考になりました!

RailsとGrapeで行う最高のWeb API開発
http://qiita.com/anoworl/items/756f01cc3d188ebad139

Grape - RailsでスピーディにAPIを作成!
http://morizyun.github.io/blog/rails-grepe-api-heroku-ruby/

32
30
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
32
30

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?