Skip to main content
1 of 3

How to rewrite recursion in a more ruby way

def get_all_friends(uid, client)
  friends = client.friendships.friends(uid: uid)
  total = friends.total_number
  get_friends(total, 0, uid, client)
end

def get_friends(total, cursor, uid, client)
  left = total
  count = [200, left].min

  friends = client.friendships.friends(uid: uid, count: count, cursor: cursor)
  left -= count
  next_cursor = friends.next_cursor

  return friends if (left == 0 || next_cursor == 0)

  more_firends = get_friends(left, next_cursor, uid, client)
  more_firends.users << friends.users
  return more_firends
end

get_all_friends(uid, observer.client).users.map do |info|
  user = User.find_or_create_by_uid_and_name(uid: info.id, name: info.name)
  follow(user)
  user
end

This code is written in a functional style. Maybe there is a more natural way to structure it with Block.

And how can I reuse the code when client.friendships.friends(uid: uid, count: count, cursor: cursor) differs?