开发者

Rails iteration with some smarts

开发者 https://www.devze.com 2023-02-09 08:59 出处:网络
I\'m putting together a little game where people are voting to see two other people are a good match based on some interests they\'ve previously entered and I\'m having trouble getting the code to do

I'm putting together a little game where people are voting to see two other people are a good match based on some interests they've previously entered and I'm having trouble getting the code to do what I want. We have some data about their "friends" and I'd like to do the following:

  1. Select one of their "friends"
  2. Find a match of that friend
  3. If I can't find any friends' matches that I previously voted on, get a random match

I'd like steps 1 and 2 to开发者_如何转开发 be somewhat random so they don't see the friend each time. I am recording the votes now, so I do have a list of their votes already. This is what I have so far, but can't figure out how to put the two together.

found_new_match = false

#Try connected users first
# connected_users = current_user.get_connected_users
connected_users = []

unless connected_users.blank?
  user = connected_users.shuffle.first
  @match = user.matches.first
end

# Here i'd like to detect whether we got through all our connections' matches
while found_new_match == false do 
  found_new_match = true if @match = current_user.get_random_new_match
end


Assuming all the supporting logic of your code (getting connected users) works correctly and your question is about how to collapse this logic into a single line, the following should work fine:

  @match = current_user.get_connected_users.shuffle.first.try(:matches).try(:first) || current_user.get_random_new_match

If you factored the "first match of a user" (user.matches.first) into its own accessor method, you could skip the terrible looking .try(:matches).try(:first). You could further factor the "first random match" into a convenience method on User, such that the code would shorten even further into:

  @match = current_user.get_random_connected_match || current_user.get_random_new_match

assuming "get_random_connected_match" does the act of getting the connected users, shuffling out an option, and extracting the first match from that. Repeat refactoring ad nauseum.


I took your advice and went with:

@match = current_user.get_random_connected_match || current_user.get_random_new_match

In my method, I have :

connected_users = self.get_connected_users.map(&:id)
my_voted_matches = self.votes.map(&:matching_id)

Matching.first(:conditions => ["id NOT IN (?) AND (user_id IN (?) OR matched_id IN (?))", my_voted_matches.join(","), connected_users.join(","), connected_users.join(",")], :order => "RAND()")
0

精彩评论

暂无评论...
验证码 换一张
取 消