2012-12-20 62 views
0

我想弄清楚在Ruby中使用多個參數的最佳方法。問題是我使用兩種類型的參數:EventUser。有時,該方法需要一個User在Ruby中使用多個參數

postAccept.replaceVariables(sally) 

有時需要兩個Users

deleteGuest.replaceVariables(sally, tom) 

有時它需要一個Event和兩個Users

addUserToEvent.replaceVariables(mEvent, tom, sally) 

而在去年,有時它需要一個Event和一個User

addnonbookable.replaceVariables(event1, carl) 

以下是我在考慮到當前的方法做:

def replaceVariables(*event) 

    if event.size <=2 

     if event[0].include?('entryId') 
      event1 = event[0] 
      my = event[1] 
     else 
      my = event[0] 
      their = event[1] 
     end 
    else 
     event1 = event[0] 
     my = event[1] 
     their = event[2] 
    end 
      ... 

的問題是,我不能想出一個辦法的userevent區分。在上面的例子中,我試圖確定對象是否有特定的鍵或值,但我得到NoMethodError

有人能告訴我我做錯了什麼,或者讓我知道保持動態和靈活的方法嗎?

def replace_variables(*args) 
    events, users = args.group_by{ |p| p.class }.values_at(Event, User) 
    #now you have 2 arrays and can manipulate them 
    #... 
end 
+2

這真是糟糕的風格。你應該用一種方法來編寫你的方法,它們接受一小部分而且相當靜態的參數。您應該爲不同的調用模式實現多種方法,對這些值進行規範化,然後調用另一種實現實際邏輯的方法(如果需要)。 –

+0

爲什麼該方法有時需要不同類型的對象? –

+0

我這樣做的原因是因爲它是更簡單的方法。該方法正在取代許多不同的環境變量。目前該方法是220行代碼。如果我把它分解成兩種方法,那會增加一倍。 – BlackHatSamurai

回答

4
def replace_variables(*args) 
    events = args.select{|a| a.is_a? Event} 
    users = args.select{|a| a.is_a? User} 
    #now you have 2 arrays and can manipulate them 
    #... 
end 

錫文在1行建議的實施。如果是,那麼這是唯一的事件,其餘的是用戶,你可以移出事件。否則,他們都是用戶。

def replaceVariables(*users) 
    event = nil 
    if users.first.is_a? Event 
    event = users.shift 
    end 
    # ... 
end 
+2

'a.is_a?事件「可能更好,因爲它允許事件的子類仍然被視爲事件。 –

+0

你是對的,我會編輯我的答案。謝謝! –

+1

這個方法的兩行可以用'events,users = params.group_by {| p | p.class} .values_at(Event,User)' –

1

檢查的第一個參數是一個事件: