LoginSignup
1
0

More than 3 years have passed since last update.

Rails/アンチパターン: 一見すると存在しないアクション

Posted at

何の変哲も無い(?)コントローラー。これはエクスポート処理関連の各種コントローラーの親クラス

controllers/export_controller.rb

class ExportController < ApplicationController

  def some_method
    やりたい処理
  end
end

そして、何もないHogeController。よく見るとExportControllerを継承している。これを見落とすとやばい

controllers/hoge_controller.rb
class HogeController < ExportController

end

最後にrouting。HogeControllerのsome_methodアクションにroutingしている

routes.rb
get '/hoge', to: 'hoge#some_method'

何が問題か

  • アクション=そのcontrollerに定義するという設計スタイルの慣れていると、ExportControllerを継承しているのを見落としガチで、その場合 「some_methodアクションなど定義されていない。routing自体が意味のないものになっている」という判断をしてしまいがち

どうあるべきか

controllers/export_controller.rb

class ExportController < ApplicationController

  def common_some_method
    やりたい処理
  end
end
controllers/hoge_controller.rb
class HogeController < ExportController

  def some_method
    common_some_method
  end
end

あるいはConcernを使う

controllers/concerns/export_concern.rb

module ExportConsern
  extend ActiveSupport::Concern

  module ClassMethods
    def common_some_method
      やりたい処理
    end
  end
end
controllers/hoge_controller.rb
class HogeController < ApplicationController
  include ExportConcern

  def some_method
    common_some_method
  end
end

など。何れにしても重要なのはHogeControllerには明示的にアクションを定義し、親クラスのメソッドが暗黙的にアクションとして呼ばれることがないようにするべき

まとめとか補足とか

  • 実際には気付ける方法は幾つかあるので、そこまで問題かというまあまあなところ
  • とにかく親クラスのメソッドをアクションとして使用するのは良くない
  • と思っていますが、実際どうなんでしょう

宣伝のようなもの

都内でRailsエンジニアでアンチパターンや失敗談を共有する会をやりたいと考えています。
conpassとかで見かけたらよろしくです。

1
0
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
1
0