使用SessionsController和RegistrationsController中的回调方法扩展基础DeviseController类

时间:2015-01-08 20:51:45

标签: ruby-on-rails ruby devise callback controller

我的问题类似于this one,但没有答案。

我想在after_filter :identify_with_segment, only: [:create]RegistrationsController < Devise::RegistrationsController添加SessionsController < Devise::SessionsController。由于这两个控制器本身都继承自DeviseController,我认为干这样做的方法是扩展DeviseController并在那里定义方法。但是,我一直收到unitialized constant错误。

我的代码:

class DeviseController < DeviseController
  def identify_with_segment
    ..
  end
end

我意识到这个类被定义的方式看起来错了。我也试过class DeviseController < Devise::DeviseController,但这也不起作用。

任何人都可以解释扩展这些其他控制器所依赖的DeviseController的正确方法吗?

1 个答案:

答案 0 :(得分:1)

如果你想打开DeviseController,你可以试试这个:

class DeviseController
   def identify_with_segment
     # ...
   end
end

很多令人困惑的事情都是以严格干燥的名义进行的,这可能就是其中之一。有时候重复自己可以让事情变得清晰,可以理解为追随你的人。

另一种选择是将此功能置于问题中,includeRegistrationsController中的SessionsController该模块。然后它明确了你正在做什么,而你并没有修改你不拥有的课程。类似的东西:

# app/controllers/concerns/whatever_it_is_this_is_doing.rb
module WhateverItIsThisIsDoing

  extend ActiveSupport::Concern

  def identify_with_segment
    # ...
  end

  included do
    after_filter :identify_with_segment, only: [:create]
  end

end

# app/controllers/registrations_controller.rb
class RegistrationsController
  include WhateverItIsThisIsDoing
end

# app/controllers/sessions_controller.rb
class SessionsController
  include WhateverItIsThisIsDoing
end
相关问题