Last Updated: February 25, 2016
·
651
· justinraczak

Simple Activity Feed for "Following" Network

This implementation is for displaying the activities of a user's "social" network assumes you have a working "follow" relationship, like Twitter. Setting that up is a separate workflow. I use this in a user's dashboard view.

First, we need to gather up all of the "activities". In my application, activities consist of creating new scores and tips. We will iterate through the user's network and collect all of these activities into an array stored in @activities.

In user.rb

def get_network_activity
  @activities = []
  @follows = self.follows.all

  @follows.each do |f|
    f.venue_scores.each do |a|
      @activities << a
    end
    f.tips.each do |t|
      @activities << t
    end
  end
  @activities
end 

Now we have all our activities collected into the @activities variable available to the view. In the view, we will iterate through the activities array and determine our formatting and/or related content by checking the class of each activity, dropping in interpolated content where we want it. (Apologies, this view code is in Slim. I will repost in ERB at a later date.)

In show.rb

- activity = resource.get_network_activity
    - activity.each do |a|
      - if a.class == VenueScore
        td = "#{User.find(a.user_id).first_name} posted a score of #{a.computed_score} to #{Venue.find(a.venue_id).name }."
      - elsif a.class == Tip
        td = "#{User.find(a.user_id).first_name} posted a tip to #{Venue.find(a.venue_id).name}."

In this example, the activity feed is part of an existing table and each activity is inserted as a <td>. It's worth noting that this is a very blunt implementation, as if a user's network is large or your application is mature, @activities may grow to contain unreasonable amounts of data. At a later date, I will post an implementation that scopes our activities to a desired timeframe, limiting the data returned in our array.

Hope you find this useful! Feel free to drop me a line on Twitter at @justinraczak if you want to chat about it or have any other ideas.