我有一个帮手,控制器和模板,如:
助手:
# app/helpers/application_helper.rb
module ApplicationHelper
def current_user
@current_user ||= User.find_by(access_token: access_token)
end
private
def access_token
pattern = /^Bearer /
header = request.headers["Authorization"]
header.gsub(pattern, "") if header && header.match(pattern)
end
end
控制器:
# app/controllers/api/v1/companies_controller.rb
class Api::V1::CompaniesController < Api::V1::BaseController
before_action :set_company, only: [:show]
def show
render @company
end
private
def set_company
@company ||= Company.find(params[:id])
end
end
# app/controllers/api/v1/base_controller.rb
class Api::V1::BaseController < ApplicationController
respond_to :json
end
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
include ApplicationHelper
protect_from_forgery with: :null_session
end
RABL-Rails模板:
object :@company
attributes :id, :name, :description, :website
# --- How can I call a helper method here?
# if (@company.owner?(current_user) or current_user.kind_of?(Admin))
# attributes :contact
# end
attributes :created_at, :updated_at
当我从RABL模板调用辅助方法时,会引发错误:
undefined local variable or method `current_user' for #<RablRails::Compiler:0x00000002494c68>
如何从RABL模板调用辅助方法?
注意:我使用了gem rabl-rails '~> 0.4.1'
。
答案 0 :(得分:0)
看起来你的调用方式是正确的,但真正的问题是你的控制器没有来自ApplicationController的继承(除非Api::V1::BaseController
中有更多我们看不到的东西)。所以这意味着您可能没有包含ApplicationHelper。
我建议您将它添加到您的控制器
class Api::V1::CompaniesController < Api::V1::BaseController
include ApplicationHelper
...
end