LoginSignup
5
6

More than 5 years have passed since last update.

garageとrails-apiを組み合わせる時のメモ

Last updated at Posted at 2015-06-09

結論

から言うと、

Gemfile
gem 'rails-api' # 投稿時点で 0.4.0
gem 'garage', github: 'cookpad/garage'  # 投稿時点で v1.5.0(tag)
gem 'responders', '~> 2.0', require: false
config/initializers/_rails_api.rb
class ActionController::API
  include ActionController::MimeResponds
  include ActionController::ImplicitRender
end

require 'responders'

こういう感じになる。(色々ツッコミ所はあるのは認めます)

なんでこうしたのか?

garageで使われているrespondersでは、controllerでrespond_toメソッドを使用しています。
rails-apiでこのメソッドを使う為にはドキュメントにもあるように、
ActionController::MimeResponds, ActionController::ImplicitRenderが必要になります。

ActionController::MimeResponds (and ActionController::ImplicitRender for Rails 4): Support for content negotiation (respond_to, respond_with).

そんな訳で、

app/controllers/application_controller.rb
class ApplicationController < ActionController::API
  include ActionController::MimeResponds
  include ActionController::ImplicitRender

  include Garage::ControllerHelper
end

と書きたくなるのだが、読み込み順の問題でこれでは思ったような結果にはなりませんでした。

全部追った訳ではないのでただの予想ですが、
少なくともconfig/initializers/garage.rbなどでGarageの設定をする前に必要な各モジュールをincludeしておけば問題なさそうです。
なので、config/initializers/_rails_api.rbなどと_から始まる名前にして早く読み込まれるようにしました。


別の話ですが、garageのgemspecにhamlとかsassとか入ってるの、なんだこれ?って思ってたんですが中に便利そうなRails Engineが入ってる為でした。

今回は用途が用途(API onlyなのでjsもcssもhtmlも不要…)なだけに、
ここを切り出して別途gemにしようと考えました。
が、garage自体が良い感じにrubygemsに登録されてないので、
切り出したgemのdependencyにgarageを書けない→テストしづらいっていう悲しみに…

5
6
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
5
6