没有看到Helper方法(Rails4引擎)



我定义了一个助手方法(用于我的rails引擎):

module Xaaron
  class ApplicationController < ActionController::Base
    protect_from_forgery with: :null_session
    rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found
    helper_method :current_user
    helper_method :authenticate_user!
    def current_user
      @current_user ||= Xaaron::User.find_by_auth_token(cookies[:auth_token]) if cookies[:auth_token]
    end
    def authenticate_user!
      if current_user
        true
      else
        redirect_to xaaron.login_path
        false
      end
    end
    protected
    def record_not_found
      flash[:error] = 'Could not find specified role'
      redirect_to xaaron.record_not_found_path
      true
    end
  end
end

据我所知,在创建辅助方法方面,上面的一切都是正确的。所以现在我需要使用这个辅助方法:

module Xaaron
  class ApiKeysController < ActionController::Base
    before_action :authenticate_user!
    def index
      @api_key = Xaaron::ApiKey.where(:user_id => current_user.id)
    end
    def create
      @api_key = Xaaron::ApiKey.new(:user_id => current_user.id, :api_key => SecureRandom.hex(16))
      create_api_key(@api_key)
    end
    def destroy
      Xaaron::ApiKey.find(params[:id]).destroy
      flash[:notice] = 'Api Key has been deleted.'
      redirect_to xarron.api_keys_path
    end
  end
end

正如您所看到的,在每次操作之前,必须对用户进行身份验证。因此authenticat_user!方法。

让我们为这个写一个测试

it "should not create an api key for those not logged in" do
  post :create
  expect(response).to redirect_to xaaron.login_path
end

我们希望,这会将我们发送回登录路径,因为我们没有登录,而且正如您所记得的,我们在API控制器中的每个操作之前都使用身份验证。我们得到的是什么:

  1) Xaaron::ApiKeysController#create should not create an api key for those not logged in
     Failure/Error: post :create
     NoMethodError:
       undefined method `authenticate_user!' for #<Xaaron::ApiKeysController:0x007f898e908a98>
     # ./spec/controllers/api_keys_controller_spec.rb:9:in `block (3 levels) in <top (required)>'

最后,我检查了我定义辅助方法的方式,即rails casts是如何做到这一点的,其他堆栈问题是如何做到的,以及rails docs是如何声明做到的——除非我错过了一些重要的步骤——为什么这不起作用?

也许我以前从未见过像这样设置的助手方法(我是rails的新手),但我看到的助手方法是在没有控制器的情况下定义的。

通常我在助手文件夹中看到这样的文件

module SessionsHelper
def sign_in(user)
remember_token = User.new_remember_token
cookies.permanent[:remember_token] = remember_token
user.update_attribute(:remember_token, User.encrypt(remember_token))
self.current_user = user
end
def current_user=(user)
@current_user = user
end
... 

然后

include SessionsHelper

在应用程序控制器中。

对我来说,这看起来像是在把控制器称为助手方法,我不确定这会有什么好处,但我想我不会。

很抱歉,如果这对没有帮助

最新更新