ActsAsActive
Acts As Active adds plug-and-play activity tracking to any ActiveRecord model, giving you instant daily stats, streak analytics, and heatmap-ready data.
It works by automatically establishing a polymorphic association with your model and generating an Activity record for each specified lifecycle event.
Installation
Install the gem and add to the application's Gemfile by executing:
bundle add acts_as_active
If bundler is not being used to manage dependencies, install the gem by executing:
gem install acts_as_active
Generators: ActsAsActive supports a metadata field in either json or jsonb format, depending on your database and preference (MySQL or PostgreSQL).
rails g acts_as_active:install --metadata=json/jsonb/auto
Usage
class Record < ApplicationRecord
acts_as_active on: [:create, :update],
if: -> { track_activity? },
unless: -> { skip_tracking? },
after_record: -> (activity) { activity.update(metadata: {be: "BOP!"}) }
end
record = Record.create!(title: "First draft")
record.update!(title: "Second draft")
record.active_today?
record.active_on?(Date.yesterday)
record.activity_count(range: 1.day.ago..Date.today)
record.heatmap(range: 1.week.ago..Date.today)
record.longest_streak
record.current_streak
Accessing Activities
record = Record.find(1)
record.activities
ActsAsActive::Activity.where(trackable: record)
ActsAsActive::Activity.all
Metadata usage
PostgreSQL
ActsAsActive::Activity.where("metadata @> ?", { source: "api" }.to_json)
ActsAsActive::Activity.where("metadata @> ?", { user: { id: 42 } }.to_json)
MySQL/SQLite
ActsAsActive::Activity.where("JSON_UNQUOTE(JSON_EXTRACT(metadata, '$.source')) = ?", "api")
ActsAsActive::Activity.where("json_extract(metadata, '$.source') = ?", "api")
Writing to metadata
activity.update!(
metadata: {
source: "api",
user: { id: 42, name: "Amit" },
tags: ["Dig", "Be", "Bop"]
}
)
Run Tests
ruby -Ilib:ruby test/test_acts_as_active.rb
Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/amitleshed/acts_as_active. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the code of conduct.
License
The gem is available as open source under the terms of the MIT License.
Code of Conduct
Everyone interacting in the ActsAsActive project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.