我試圖將我的控制器邏輯包裹在同一個條件下。我不知道如何實作,因為我對Ruby on rails有點陌生。下面的偽代碼是我想要實作的
。class Api::BaseController<
include Api::AuthConcern if SAME_CONDITION
before_action -> { some_function() } if SAME_CONDITION
if SAME_CONDITION
rescue_from Api::AuthConcern::Unauthenticated do |e|
呈現 status: 401, json: { error: e.error }
end
rescue_from Api::AuthConcern::PermissionDenied do |e|
渲染 status: 403, json: { error: e.error }
end
end
end end
uj5u.com熱心網友回復:
你不需要它。只需使用方法來代替:
module Api
# 避免在你的模塊名稱中加入 "關注"。
# 它完全沒有提供關于該物件的資訊。
module AuthConcern
擴展ActiveSupport::Concern
包括do
rescue_from Unauthenticated { |e| respond_to_unauthenticated(e.error) }
rescue_from PermissionDenied { |e| respond_to_permission_denied(e.error) }
end
def respond_to_unauthenticated(message)
渲染 status: 401, json: { error: message }
end
def respond_to_permission_denied(message)
渲染 status: 403, json: { error: message }
end
end
end end
這使得任何包含該模塊的類可以通過簡單地覆寫該方法來定制行為:
這使得任何包含該模塊的類可以通過簡單地覆寫該方法來定制行為:
module Api
class FooController < BaseController
# ...
私有的
def respond_to_unauthenticated(錯誤)
呈現 plain: '哦不,你弄壞了!'
結束。
end
end end
如果你需要添加更多的邏輯到一個模塊如何增強類中,你可以使用宏模式。這只是一個為類添加方法或行為的類方法。
module Api<
module AuthConcern
擴展ActiveSupport::Concern
# ....
module ClassMethods
def authenticate! (**kwargs)
before_action :authenticate!, **kwargs
end
end
end end
end end
module Api
class FooController < BaseController
認證! except: :index
結束
end end
這種模式在Ruby中隨處可見,從attr_accessor到Rails callbacks和assocations。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/307008.html
標籤:
上一篇:在reactjs中使用狀態點擊按鈕時切換類,而不需要重新渲染組件
下一篇:如何從規范檔案中傳遞數值到控制器
