Reputation: 23483
I am trying to figure out the best way to use multiple parameters in Ruby
. The problem is that I am using two types of parameters: Event
and User
. Sometimes the method needs one User
:
postAccept.replaceVariables(sally)
Sometimes it needs two Users
:
deleteGuest.replaceVariables(sally, tom)
Sometimes it needs an Event
and two Users
:
addUserToEvent.replaceVariables(mEvent, tom, sally)
And last, sometimes it needs one Event
and one User
:
addnonbookable.replaceVariables(event1, carl)
Here is what I am doing currently in regard to the method:
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
...
The problem is, I can't figure out a way to differentiate between the user
and the event
. In the example above, I tried to determine if the object has a specific key, or value, but I get NoMethodError
.
Can someone tell me what I'm doing wrong, or show me a way to keep things dynamic and flexible?
Upvotes: 0
Views: 298
Reputation: 2016
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
Tin Man suggested implementation in 1 line:
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
Upvotes: 4
Reputation: 176655
Check if the first argument is an event. If it is, then it is the only event, and the rest are users, and you can shift out the event. Otherwise, all of them are users.
def replaceVariables(*users)
event = nil
if users.first.is_a? Event
event = users.shift
end
# ...
end
Upvotes: 1