我正在處理一個有很多before_actions的控制器的應用程序。它們中的大多數通過它們設置的實例變量彼此連接。例如:多個before_action調用錯誤的代碼風格嗎?
def first_action
@first_variable = Something.new
end
def second_action
if @first_variable
@second_variable = Other.new
end
end
控制器看起來是這樣的:
class ExampleController < ApplicationController
before_action :first_action, only: [:index, :show, :create]
before_action :second_action, only: [:index, :show, :create]
before_action :third_action, only: [:index, :show, :create]
before_action :fourth_action, only: [:index, :show, :create]
before_action :fifth_action, only: [:index, :show, :create]
before_action :sixth_action, only: [:index, :show, :create]
before_action :seventh_action, only: [:index, :show, :create]
def index
# some code
end
def show
# some code
end
def create
# some code
end
private
# all of the before_action methods
end
這真的很難但從我的角度來理解。每種方法都有很多代碼。另外還有一些控制器可以繼承這個控制器,也可以使用部分或全部這些動作。
我聽說它的更好更明確一些在每個方法加載變量,但這樣的:
class ExampleController < ApplicationController
def index
first_action
second_action
third_action
fourth_action
fifth_action
sixth_action
seventh_action
# some code
end
def show
first_action
second_action
third_action
fourth_action
fifth_action
sixth_action
seventh_action
# some code
end
def create
first_action
second_action
third_action
fourth_action
fifth_action
sixth_action
seventh_action
# some code
end
private
# all of the before_action methods
end
不看要好得多。有沒有一種方法來重構它以提高可讀性,還是應該堅持使用當前的解決方案?
有多個'before_actions'沒有什麼錯 - 但它看起來更像是你有一個情況,他們可以收集到一個動作? – Matt
我帶着你的想法@Matt去了謝謝,如果你添加它作爲答案,我可以檢查它作爲我的問題的解決方案:) – zeth
完成,很高興聽到它幫助! – Matt