/ gem

public_activity gem

public_activity is the best gem for easy activity tracking of models and easy to integrate in your rails application.

links: Github-doc, Demo

STEPS:

  1. In your gemfile:
gem 'public_activity'
  1. Generate migration for activities and migrate the database (in your Rails project):
rails g public_activity:migration
rake db:migrate 
  1. Include PublicActivity::Model and add tracked to the model you want to keep track of:
class Answer < ActiveRecord::Base
  include PublicActivity::Model
  tracked
end

now, by default create/update/destroy activities are recorded in activities table.(basic CRUD actions)

  1. Displaying activities: (see more details)

controller:

def index
  @activities = PublicActivity::Activity.all
end

views: public_activity looks for views in app/views/public_activity.

 = render_activities(@activities) 

CUSTOM ACTIVITIES:

You can trigger custom activities by setting all your required parameters and triggering create_activity on the tracked model, like this:

@answer.create_activity key: 'article.commented_on', owner: current_user

SET THE ACTIVITY'S OWNER TO current_user BY DEFAULT: (see more details)

class Answer < ActiveRecord::Base include PublicActivity::Model
  tracked only: [:create], owner: -> (controller, model) { model.user }
end

DESTROY STALE ACTIVITIES:

If you are not tracking the destroy, do not forget to add callback to remove the activity associated to that activerecord.

before_destroy :remove_activity
def remove_activity
  activity = PublicActivity::Activity.find_by_trackable_id(self.id)
  activity.destroy if activity.present?
  true
end

CUSTOMIZE ACTIVITY MODEL:

If you want to add your own custom scopes, for example to display activities of current-user or friends activites

class Activity < PublicActivity::ORM::ActiveRecord::Activity
  def self.user_activities(user)
    where("activities.owner_id = ? AND owner_type = 'User'", user.id)
  end
end

Swati Jadhav

I am a Rubyist, ROR developer, passionate about change and trying new things, both professionally and in general with life. Currently, working on Ember.js applications and fasci...

Read More