Giter VIP home page Giter VIP logo

notifications's Introduction

Notifications

Mountable notifications for any Rails applications.

Gem Version Build Status codecov.io

Example:

2016-03-29 10 48 16

Installation

$ bundle add notifications

You now have a notifications generator in your Rails application:

$ rails g notifications:install

You can generate views, controllers if you need to customize them:

$ rails g notifications:views
$ rails g notifications:controllers

Usage

Create a Notification

class User
  def follow(user)
    Notification.create(notify_type: 'follow', actor: self, user: user)
  end
end

class Comment
  belongs_to :post
  belongs_to :user

  after_commit :create_notifications, on: [:create]
  def create_notifications
    Notification.create(
      notify_type: 'comment',
      actor: self.user,
      user: self.post.user,
      target: self)
  end
end

Get unread notifications count for a user:

# unread count
unread_count = Notification.unread_count(current_user)

# read count
read_count = Notification.read_count(current_user)
# for non-user class
Notifications.config.user_class = 'Member'

#or change

Notifications.configure do
  # Class name of you User model, default: 'User'
  self.user_class = 'User'

  # Method of user name in User model, default: 'name'
  # self.user_name_method = 'name'

  # Method of user avatar in User model, default: nil
  # self.user_avatar_url_method = nil

  # Method name of user profile page path, in User model, default: nil
  # self.user_profile_url_method = 'profile_url'

  # authenticate_user method in your Controller, default: nil
  # If you use Devise, authenticate_user! is correct
  # self.authenticate_user_method = 'authenticate_user!'

  # current_user method name in your Controller, default: 'current_user'
  # If you use Devise, current_user is correct
  # self.current_user_method = 'current_user'
end

Write your custom Notification partial view for notify_types:

If you create a notify_type, you need to add a partial view in app/views/notifications/ path, for example:

# There have two notify_type
Notification.create(notify_type: 'follow' ....)
Notification.create(notify_type: 'mention', target: @reply, second_target: @topic, ....)

Your app must have:

  • app/views/notifications/_follow.html.erb
  • app/views/notifications/_mention.html.erb
# app/views/notifications/_follow.html.erb
<div class="media-heading">
  <%= link_to notification.actor.title, main_app.user_path(notification.actor) %> just followed you.
</div>
# app/views/notifications/_mention.html.erb
<div class="media-heading">
  <%= link_to notification.actor.title, main_app.user_path(notification.actor) %> has mentioned you in
  <%= link_to notification.second_target.title, main_app.topic_path(notification.second_target) %>
</div>
<div class="media-content">
  <%= notification.target.body %>
</div>

NOTE: When you want use Rails route path name in notification views, you must use main_app prefix. etc: main_app.user_path(user)

About Notification template N+1 performance

It is recommended that you use second_level_cache for solving N+1 performance issues.

Contributing

Testing for multiple Rails versions:

make test_51
# or test all
make test

Site Used

License

The gem is available as open source under the terms of the MIT License.

notifications's People

Contributors

asiansteev avatar davidzhu001 avatar eric-guo avatar gagangupta19 avatar huacnlee avatar joaumg avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

notifications's Issues

Rails 4.2.8 probelm with optional: true

I've got a problem and I get:

Unknown key: :optional. Valid keys are: :class_name, :anonymous_class, :foreign_key, :validate, :autosave, :dependent, :primary_key, :inverse_of, :required, :foreign_type, :polymorphic, :touch, :counter_cache

I tried solving it this way and I reopened module in lib directory and added code like this:

module Notifications
  module Model
    included do
      belongs_to :actor, class_name: Notifications.config.user_class
      belongs_to :user, class_name: Notifications.config.user_class

      belongs_to :target, polymorphic: true
      belongs_to :second_target, polymorphic: true
      belongs_to :third_target, polymorphic: true

      scope :unread, -> { where(read_at: nil) }
    end
  end
end

But it still doesn't work.

will_paginate 很怪的依赖

#2 提出了will_paginate,除此之外,还有 puma mysql2 bootstrap,看不明白为什么需要这些 gem。严格来说,devise 都不应该依赖。但是考虑到这种场景,依赖也无所谓。上面四个确实想不明白,这种依赖,基本没办法让别人通用了。

Example App?

Can you create a tutorial app that shows how you connect your notifications to various models? acts_as_commentable_with_threading / acts_as_follower / posts, etc. Also, it would be nice to know how use this gem alongside actioncable.

Nav Partial is not working in Notifications Controller

I'm unable to reach the notifications controller when I click on the link for it. I'm getting ActionView::Template::Error (undefined local variable or method 'dashboard_index_path' for #<#<Class:0xdccbba0>:0xdcc2e40>): for some unknown reason. Do I have to define something inside of the notifications_controller.rb?

searching the partial in the gems?

ActionView::MissingTemplate in Notifications::Notifications#index
Showing /home/daniel/jexts/app/views/notifications/notifications/_notification.html.erb where line #11 raised:

Missing partial notifications/_comment with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :coffee, :jbuilder]}. Searched in:
  * "/home/daniel/jexts/app/views"
  * "/home/daniel/.rbenv/versions/2.5.0/lib/ruby/gems/2.5.0/gems/kaminari-core-1.1.1/app/views"
  * "/home/daniel/.rbenv/versions/2.5.0/lib/ruby/gems/2.5.0/gems/notifications-0.6.0/app/views"
  * "/home/daniel/.rbenv/versions/2.5.0/lib/ruby/gems/2.5.0/gems/mailboxer-0.15.1/app/views"
  * "/home/daniel/.rbenv/versions/2.5.0/lib/ruby/gems/2.5.0/gems/devise-4.4.1/app/views"

Deployment on heroku: alias_method 'current_user' undefined

The integration works fine in development, but this is preventing my app from starting in heroku

I see that the codebase does define current user in the controller, but it seems to be breaking during the startup of the app after the build.

I am using devise 4.6.2, rails 5.2, ruby 2.6.0

2019-08-11T07:27:05.920574+00:00 heroku[web.1]: State changed from crashed to starting
2019-08-11T07:27:10.246313+00:00 heroku[web.1]: Starting process with command `bin/rails server -p 23752 -e production`
2019-08-11T07:27:15.427833+00:00 heroku[web.1]: State changed from starting to crashed
2019-08-11T07:27:15.409030+00:00 heroku[web.1]: Process exited with status 1
2019-08-11T07:27:15.316165+00:00 app[web.1]: /app/vendor/bundle/ruby/2.5.0/gems/notifications-0.6.1/app/controllers/notifications/application_controller.rb:5:in `alias_method': undefined method `current_user' for class `Notifications::ApplicationController' (NameError)

I do see it in https://github.com/rails-engine/notifications/blob/master/app/controllers/notifications/application_controller.rb I am using the defaults for current_user and authenticate_user!

could it be that it is getting loaded before devise?

Unable to create notifications for user's followers

Hi! I implemented follow relationships to my app with this tutorial.

While trying to create notifications for user's followers whenever the person they follow posts a new chapter but i keep getting error
User(#137278760) expected, got #<ActiveRecord::Associations::CollectionProxy [#<User id: 3, name: "Otunba Olusaga of Saganation", username: "saga", email: "[email protected]", created_at: "2019-03-26 11:59:16", updated_at: "2019-03-26 16:40:18", admin: false, bio: "">]> which is an instance of User::ActiveRecord_Associations_CollectionProxy(#137276280)

here is the code:
after_commit :create_notifications, on: :create

private

def create_notifications
    Notification.create do |notification|
        notification.notify_type = 'chapter'
        notification.actor = self.book.user
        notification.user = self.user.followers
        notification.target = self
        notification.second_target = self.book
    end
end

Little typo?

class Comment
belongs_to :post
belongs_user :user ???
Thanks for the gem..

How do I exclude notification.actor from recieveing notifications?

Hello! I'm creating notifications for a whenever a book review is submitted like so..

   after_commit :create_notifications, on: :create

    def create_notifications
        Notification.create do |notification|
            notification.notify_type = 'new_review'
            notification.actor = self.user
            notification.user = self.book.user
            notification.target = self
            notification.second_target = self.book
        end
    end

Things work fine but the notification.actor also gets notified. How do I exclude the actor? Thanks!

How do I create notifications for comment replies?

Hi! I've threaded commentable comment system on my app. I've been able to create notifications for a new comment. However, whenever a reply is added to a comment, the self.post.user for example gets the notification as a new comment. So my question is how do I create notification for replies too in such a way that when a reply is posted on a comment, the owner of the comment and the self.post.user should get notified of a reply and now as new comment?

comment.rb

class Comment < ApplicationRecord
  belongs_to :commentable, polymorphic: true
  belongs_to :user
  belongs_to :parent, class_name: 'Comment', optional: true
  has_many :replies, class_name: 'Comment', foreign_key: :parent_id, dependent: :destroy

  validates :content, presence: true, length: { maximum: 255 }

  after_commit :notify_comment_created, on: [:create]
  def notify_comment_created
    return if self.commentable.blank?
    receiver_id = self.commentable&.user_id
    return if receiver_id.blank?
    # notified_user_ids = self.mentioned_user_ids || []
    # return if notified_user_ids.include?(receiver_id)

    Notification.create(
      notify_type: "comment",
      target: self,
      second_target: self.commentable,
      actor_id: self.user_id,
      user_id: receiver_id
    )
  end
end

How do I create a notification partial for this view?

I've already setup a notification for whenever a user posts a review on a book, the book.user gets notified in this partial: views/notifications/_book.html.erb. At the same time, I trying to create notification to a user's followers for whenever the user they're following posts a new book. IMO, supposed to create a book partial to render the notification view but I already have a duplicate of the book partial to show reviews notifications. Now I don't know if I can still tweak in in the same file or create something else.

I've implemented following relationships which is working well on my app from this tutorial https://www.devwalks.com/lets-build-instagram-with-ruby-on-rails-part-6-follow-all-the-people/

This is what I've done so far with the codes

user.rb

  has_many :books, dependent: :destroy
  has_many :chapters, dependent: :destroy
  has_many :reviews, dependent: :destroy
  has_many :genres
  has_many :ratings

review.rb

belongs_to :book
belongs_to :user

after_commit :create_notifications, on: :create

private

def create_notifications
   Notification.create do |notification|
       notification.notify_type = 'book'
       notification.actor = self.user
       notification.user = self.book.user
       notification.target = self
       notification.second_target = self.book
    end
end

views/notifications/_book.html.erb

<div class=''>
 <%= link_to notification.actor.username, main_app.profile_path(notification.actor.username) %> reviewed
<%= link_to notification.second_target.title, main_app.book_path(notification.second_target) %>
</div>

<div class=''>
   <% unless notification.target.blank? %>
      <div class="review-rating" data-score="<%= notification.target.rating %>"></div>
      <%= notification.target.comment %>
  <% end %>
</div>

book.rb

belongs_to :user
has_many :chapters, dependent: :destroy

after_commit :create_notifications, on: :create

def create_notifications
    self.user.followers.each do |follower|
      Notification.create(notify_type: 'book', 
                          actor: self.user,
                          user: follower, 
                          target: self, 
                          second_target: self.book)

    end
end

So, if I've to render in the same partial, how should I? or maybe I've to do it another way?

Dependency of Will Paginate vs kaminari

Hello! This gem looks great and I'd love to introduce it into my application. Is there any way to remove the dependency of kaminari in favor of will_paginate? My application currently uses will_paginate and it will be hard to change. Thanks in advance!

How to create notifications for this custom following relationships.

Hi! I created a following relationship on my app and I'm trying to create notifications for the current_user whenever followed by another user.
I've tried to implement but notifications are not creating. It seems to be different for other types I've created.

user.rb

has_many :follower_relationships, foreign_key: :following_id, class_name: 'Follow'
  has_many :followers, through: :follower_relationships, source: :follower

  has_many :following_relationships, foreign_key: :follower_id, class_name: 'Follow'
  has_many :following, through: :following_relationships, source: :following

  def follow(user_id)
    following_relationships.create(following_id: user_id)
  end

  def unfollow(user_id)
    following_relationships.find_by(following_id: user_id).destroy
  end

relationships_controller

class RelationshipsController < ApplicationController
  def follow_user
    @user = User.find_by! username: params[:username]
    if current_user.follow @user.id
      respond_to do |format|
        format.html { redirect_to root_path }
        format.js
      end
    end
  end

  def unfollow_user
    @user = User.find_by! username: params[:username]
    if current_user.unfollow @user.id
      respond_to do |format|
        format.html { redirect_to root_path }
        format.js
      end
    end
  end
end

follow.rb

class Follow < ApplicationRecord
	belongs_to :follower, foreign_key: 'follower_id', class_name: 'User'
  	belongs_to :following, foreign_key: 'following_id', class_name: 'User'
end

I've tried this with the codes below but it's not working
user.rb

after_commit :create_notifications, on: :follow

  private

  def create_notifications
    self.user.following.each do |follower|
      Notification.create(notify_type: 'new_follower', actor: self, user: user)
 
    end
  end

  after_commit :create_notifications, on: :follow

  private

and also this in notify.rb

# Auto generate with notifications gem.
class Notification < ActiveRecord::Base
  include Notifications::Model

  def self.notify_follow(user_id, follower_id)
    opts = {
      notify_type: "follow",
      user_id: user_id,
      actor_id: follower_id
    }
    return if Notification.where(opts).count > 0
    Notification.create opts
  end
end

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.