Created
October 11, 2017 10:13
-
-
Save pieterjongsma/ef30084659ea06a80c2ea47187f98f12 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class EventWithFriends | |
def initialize(object, attending_friends_by_user_id) | |
super(object) | |
@attending_friends_by_user_id = attending_friends_by_user_id | |
end | |
def attending_friends_for_user(user) | |
@attending_friends_by_user_id[user.id] || super(user) | |
end | |
end | |
class EventsFeed | |
def initialize(events:, user:) | |
@user = user | |
@events = events | |
@friend_cache = build_friend_cache | |
end | |
def events | |
@events.map { |event| EventWithFriends.new(event, @user.id => @friend_cache[event.id]) } | |
end | |
private | |
def build_friend_cache | |
friend_hash = {} | |
all_friends = friends | |
@events.each do |event| | |
friend_hash[event.id] = all_friends.select { |friend| friend.event_id == event.id } | |
end | |
friend_hash | |
end | |
def friends | |
return [] if @events.empty? # Possible scenario in our app | |
@user.friends.joins(:attendances).where(attendances: { event_id: @events.ids }).select(‘“users”.*’, ‘“attendances”.”event_id”’) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment