Ruby on Rails的skip_before_action无法按预期工作

时间:2014-12-22 11:41:30

标签: ruby-on-rails doorkeeper

有两个名称空间:

api/public
api/mobile

在公共控制器中创建具有适当范围的门卫授权。例如:

class API::Public::PostsController < ApplicationController
  before_action -> { doorkeeper_authorize! :public }

  def show
    @post = Post.find(params[:id])
  end
end

移动命名空间中的控制器继承自公共命名空间中的控制器。例如:

class API::Mobile::PostsController < API::Public::PostsController
  skip_before_action :doorkeeper_authorize!
  before_action -> { doorkeeper_authorize! :mobile }
end

所以重点在于功能相同,如果移动设备存在一些差异,则可以在移动命名空间中覆盖操作。 问题是这两个名称空间的范围不同,但跳过了doorkeeper_authorize!不起作用。

有没有办法解决这个问题?

2 个答案:

答案 0 :(得分:4)

你可以在lambda中调用一个返回授权内容的方法:

class API::Public::PostsController < ApplicationController
  before_action -> { doorkeeper_authorize! authorization_scope }

  def show
    @post = Post.find(params[:id])
  end

  protected
    def authorization_scope
      :public
    end
end

然后你的子类只需覆盖方法而不会陷入skip_before_filter痛苦

class API::Mobile::PostsController < API::Public::PostsController
  protected
    def authorization_scope
      :mobile
    end
end

答案 1 :(得分:3)

skip_before_filter适用于跳过方法,而不是跳过lambdas / procs。尝试创建公共授权方法:

class API::Public::PostsController < ApplicationController
  before_action :authorize_public

  ...

  def authorize_public
    doorkeeper_authorize! :public
  end
end

class API::Mobile::PostsController < API::Public::PostsController
  skip_before_action :authorize_public
  ...
end