在rails中,我有一个定义http_basic_authentication_with
的基本控制器,我希望在子类中有一个特定的路径跳过。这与我指定控制器skip_before_filter
的方式类似。这可能吗?
我的基本控制器看起来像这样:
class BaseController < ApplicationController
http_basic_authenticate_with name: "name", password: "password"
end
我有一个继承自的控制器:
class HomeController < BaseController
def index
end
def no_auth
end
end
我希望“index”需要基本身份验证,但“no_auth”不需要。
谢谢!
答案 0 :(得分:2)
我将如何做到这一点。
class BaseController < ApplicationController
http_basic_authenticate_with name: "name", password: "password"
end
让我们用自己的类方法替换http_basic_authenticate_with
。我们称之为auth_setup
。
class BaseController < ApplicationController
auth_setup
def self.auth_setup
http_basic_authenticate_with name: "name", password: "password"
end
end
由于我们不想在每个子类中调用它,我们只能将参数提取到其他方法。我们称之为auth_params。
class BaseController < ApplicationController
auth_setup
def self.auth_setup
http_basic_authenticate_with auth_params
end
def self.auth_params
{ name: 'name', password: 'password' }
end
end
从现在开始,我们可以使用此方法修改子类中的auth参数。例如:
class HomeController < BaseController
def index
end
def no_auth
end
def self.auth_params
(super).merge(except: :index)
end
end
但是,Ruby类定义中的方法调用不会被继承(很容易忘记使用Rails样式的 )。根据{{1}}的实施情况,您需要另一个修复 - http_basic_authenticate_with
回调。
inherited
希望它有所帮助!