`<class:xxxxxxx>': uninitialized constant xxxxxxx::ooooooo(NameError)を解決した話


実践Ruby on Rails4を勉強していて出てきたエラーを解決した話。

起きたこと

controllers/concernsの中に、

errors_handler.rb
module ErrorHandlers
  extend ActiveSupport::Concern

  included do
    rescue_from Exception, with: :rescue500
    rescue_from ApplicationController::Forbidden, with: :rescue403
    rescue_from ApplicationController::IpAddressRejected, with: :rescue403
    rescue_from ActionController::RoutingError, with: :rescue404
    rescue_from ActiveRecord::RecordNotFound, with: :rescue404
  end

  private
  def rescue403(e)
    @exception = e
    render 'errors/fobidden', status: 403
  end

  def rescue500(e)
    @exception = e
    render 'errors/internal_server_error', status: 500
  end

  def rescue404(e)
    @exception = e
    render 'errors/not_found', status: 404
  end
end

を作って、application_controller.rbを

application_controller.rb
class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  layout :set_layout

  class Forbidden < ActionController::ActionControllerError; end
  class IpAddressRejected < ActionController::ActionControllerError; end

  include ErrorHandlers if Rails.env.production?

  private
  def set_layout
    if params[:controller].match(%r{\A(staff|admin|customer)/})
      Regexp.last_match[1]
    else
      'customer'
    end
  end
end

このようにしてErrorHandlersをincludeしたかったのですが、

/vagrant/app/controllers/application_controller.rb:11:in `class:ApplicationController': uninitialized constant ApplicationController::ErrorHandlers (NameError)

と出てきてしまいました。

Rubyでのハマりポイント
を見ても、モデルの命名の話じゃない。他の記事を参照してもどれもピンときませんでした。

結果

concernsの下のファイルの名前が、

errors_handler.rb

だったのがいけなかったという話でした。

error_handlers.rb

にしなければいけないという、単純に自分のミスです。

includeするときにファイルの名称なんて気にする必要なく、module ErrorHandlersって書いていれば読み込んでくれるものかと思っていましたが、そんなことはないんですね(初心者並感)。

先にここだけアウトプットしておくので、また調べてから更新します。