2015-05-12 17 views
1

我在我的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方法。

+0

DEF car_color(角色) COLORS = { 「客戶」=> 「紅」, 「管理員」=> 「藍」, 「其他」=> 「綠色」} COLORS [作用] 端 你可以也把這個顏色數組放在你的用戶模型中,並且可以在這裏訪問。 –

+0

def car_state(state) if current_user.is_customer? 「汽車」 其他 「車車 - #{state.gsub(」」,‘ - ’)}」 結束 結束 –

回答

2

我看不出有任何問題與輔助方法檢查當前用戶的角色。

您可以將檢查行爲轉移到用戶模式,雖然這會使事情更清潔的(當然,你可能想概括這種多角色):

class User < ActiveRecord::Base 
    def is_customer? 
    self.roles.include?('customer') 
    end 
end 

然後在你的幫助,你可以只檢查current_user.is_customer?

def car_color(state) 
    if current_user.is_customer? 
    'car' 
    else 
    if state == 'in service' 
     'car car-in-service' 
    elsif state == 'in garage' 
     'car car-in-garage' 
    else 
     'car' 
    end 
    end 

我覺得它有用,有時以建立類的數組過這往往是清潔的(我在的情況下拋出太):

def car_color(state) 
    car_classes = ['car'] 
    unless current_user.is_customer? 
    car_classes << case state 
     when 'in service' then 'car-in-service' 
     when 'in garage' then 'car-in-garage' 
    end 
    end 
    car_classes.join(" ") 
end 
+0

我喜歡這一點,但是當幫手被稱爲像在一個視圖中30條領帶會發生什麼? 'current_user.is_customer?'每次都打db,還是以某種方式緩存? – user2936314

+1

如果你看看你的日誌,你應該看到'CACHE(0.0ms)'針對第二個和後續查詢的任何'is_customer?'檢查。這是因爲默認打開了查詢緩存。 (另見:http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/QueryCache.html#method-i-cache - 無法找到一個非常好的鏈接) – Shadwell