Comment passer des méthodes à Ruby Map
Oct 09 2020
J'ai le code suivant:
wedding = Wedding.where(location_id: user_params[:locationId])
wedding.map(&:guests).each do |member|
user_ids << member.ids
end
Dans mon cas, il :guestsy a une table d'enregistrement active, mais j'en ai quelques-uns que je voudrais passer mappour générer leuser_ids
Ce serait donc un tableau de méthodes comme celle-ci, que je voudrais passer: [guests, bride, etc etc]
Ce serait encore mieux si je pouvais passer tout le tableau, mais sinon, si je pouvais parcourir le tableau de méthodes, ce serait bien aussi.
Des idées?
EDIT: J'essaye ça sans chance .. j'obtiens: NameError (wrong constant name guests):
roles = ["guests"]
wedding = Wedding.where(location_id: user_params[:locationId])
roles.each do |role|
clazz = Kernel.const_get(role)
wedding.map(&:clazz).each do |member|
user_ids << member.ids
end
end
Réponses
2 PhiAgent Oct 09 2020 at 17:46
Ci-dessous, je transmets un éventail de méthodes aux membres du tableau des mariages:
weddings = Wedding.where(location_id: user_params[:locationId])
# array with methods you're interested in
methods=[:guests, :bride]
# looping through the weddings array
weddings.each do |wedding|
# looping through the methods array
methods.each do |method|
# for each wedding, passing every method to the wedding
members=wedding.public_send(method)
members.each do |member|
# storing the values
user_ids << member.ids
end
end
end