我在我的Rails應用程序,其基於對象的狀態的CSS class
,像有一個簡單的幫手:在條件語句工作軌道幫手
<li class='<%= car_color(car.state) %>'><%= car.model %></li>
在幫助它基本上是:
它適用於我的用例。然而,如何有一個新的要求User
角色customer
不應該看到這個幫手創建的顏色編碼。
我首先想到的是做一次檢查在控制器中看到,如果用戶應該能夠看到的顏色編碼:
class CarsController < ApplicationController
before_action :is_customer?
# bunch of restful stuff
private
def is_customer?
@customer if current_user.roles.include? 'customer'
end
end
然後在我的幫助,我可以只添加一行:
def car_color(color)
return 'car' if @customer
end
這符合要求,但它聞起來給我。現在我的幫手對@customer
有一個依賴關係,它僅僅因爲它是一個實例變量而被傳遞。另一種方法是明確地將user.role
傳遞給car_color
,或者將條件中的所有調用都打包爲car_color
,這些條件基於user.role,這看起來更糟糕。
有沒有一種方法可以幫助您根據不同的用戶角色準備更多條件的代碼?我的想法是做這樣的事情:
module CarHelper
def car_color(args)
set_color_for_role(args[:user_role]) if args[:user_role]
set_color_for_state(args[:car_state]) if args[:car_state]
end
private
def set_color_for_role(user_role)
# stuff
end
def set_color_for_state(car_state)
# stuff
end
end
我不使用導軌傭工經常因爲我主要是在角工作,我想知道如果我失去了一個更清潔的OOP方法。
DEF car_color(角色) COLORS = { 「客戶」=> 「紅」, 「管理員」=> 「藍」, 「其他」=> 「綠色」} COLORS [作用] 端 你可以也把這個顏色數組放在你的用戶模型中,並且可以在這裏訪問。 –
def car_state(state) if current_user.is_customer? 「汽車」 其他 「車車 - #{state.gsub(」」,‘ - ’)}」 結束 結束 –