Is it possible to use the gem Unread with the gem Public Activity?

1.2k Views Asked by At

I am currently using the gem 'Public Activity', and in the view I have a users activity filtered to only show that user the activities that apply to them, such as 'John Smith commented on your post'. However, I would like to add notifications to this, like facebook or twitter, where a badge shows a number, and when you see the feed the badge disappears.

I have found a gem called Unread which looks ideal, except it requires adding acts_as_readable :on => :created_at to your model, and as I'm using the public_activity gem the class is not accessible to add this.

Is it possible to inject the code the unread gem requires, into the PublicActivity:Activity class?

Links:

gem public_activity: https://github.com/pokonski/public_activity

gem unread: https://github.com/ledermann/unread

2

There are 2 best solutions below

0
On BEST ANSWER

To anyone that may find this in future, i implemented a completely different system by data modelling my own notifications. Rather than using public activity and unread, I made a new model called notifications. This had the columns:

    recipient:integer
    sender:integer
    post_id:integer
    type:string
    read:boolean

Then, whenever I had a user comment or like etc, I built a new notification in the controller, passing in the following information:

    recipient = @post.user.id
    sender = current_user.id
    post_id = @post.id
    type = "comment"    # like, or comment etc
    read = false        # read is false by default

In the navigation bar I simply added a badge that counted the current_users unread notifications, based on an application controller variable.

    @unreadnotifications = current_user.notifications.where(read: false)

    <% if @unreadnotifications.count != 0 %>
        (<%= @unreadnotifications.count %>)
    <% end %>

Then, in the notifications controller I had it run a mark_as_read action on the view. This then set the notification count back to 0.

    before_action :mark_as_read

    def mark_as_read
        @unread = current_user.notifications.where(read: false)
        @unread.each do |unread|
            unread.update_attribute(:read, true)
        end
    end
0
On

It's actually possible to add extra stuff to the PublicActivity::Class like this:

Add this file called public_activity.rb to config/initializers.

PublicActivity::Activity.class_eval do
  acts_as_readable :on => :created_at

  def self.policy_class
    ActivityPolicy
  end
end

I've also included a snippet in there for anyone using Pundit with Public Activity so that you can just have an activity_policy.rb policy file.

NOTE: Be sure to use the latest version of Public Activity that includes this line: https://github.com/chaps-io/public_activity/blob/1-5-stable/lib/public_activity/orm/active_record/activity.rb#L9 because without base_class set, Unread will use the wrong polymorphic class name.