├── spec ├── dummy │ ├── log │ │ └── .keep │ ├── app │ │ ├── mailers │ │ │ ├── .keep │ │ │ └── notifications_mailer.rb │ │ ├── models │ │ │ ├── .keep │ │ │ ├── concerns │ │ │ │ └── .keep │ │ │ ├── user.rb │ │ │ └── message.rb │ │ ├── assets │ │ │ ├── images │ │ │ │ └── .keep │ │ │ ├── javascripts │ │ │ │ └── application.js │ │ │ └── stylesheets │ │ │ │ └── application.css │ │ ├── views │ │ │ ├── notifications_mailer │ │ │ │ ├── abc.html.erb │ │ │ │ └── notify_new_message.html.erb │ │ │ ├── notifications │ │ │ │ ├── _admin_user_created.html.erb │ │ │ │ └── _notify_new_message.html.erb │ │ │ ├── wupee │ │ │ │ ├── notifications │ │ │ │ │ └── _notify_new_message.html.erb │ │ │ │ └── api │ │ │ │ │ └── notifications │ │ │ │ │ ├── _notify_new_message.json.jbuilder │ │ │ │ │ ├── show.json.jbuilder │ │ │ │ │ ├── index.json.jbuilder │ │ │ │ │ └── _notification.json.jbuilder │ │ │ └── layouts │ │ │ │ └── application.html.erb │ │ ├── helpers │ │ │ └── application_helper.rb │ │ └── controllers │ │ │ ├── notifications_controller.rb │ │ │ └── application_controller.rb │ ├── lib │ │ └── assets │ │ │ └── .keep │ ├── public │ │ ├── favicon.ico │ │ ├── 500.html │ │ ├── 422.html │ │ └── 404.html │ ├── bin │ │ ├── rake │ │ ├── bundle │ │ ├── rails │ │ └── setup │ ├── config │ │ ├── locales │ │ │ └── en.yml │ │ ├── initializers │ │ │ ├── cookies_serializer.rb │ │ │ ├── session_store.rb │ │ │ ├── mime_types.rb │ │ │ ├── filter_parameter_logging.rb │ │ │ ├── wupee.rb │ │ │ ├── backtrace_silencers.rb │ │ │ ├── assets.rb │ │ │ ├── wrap_parameters.rb │ │ │ └── inflections.rb │ │ ├── environment.rb │ │ ├── routes.rb │ │ ├── boot.rb │ │ ├── database.yml │ │ ├── secrets.yml │ │ ├── application.rb │ │ └── environments │ │ │ ├── development.rb │ │ │ ├── test.rb │ │ │ └── production.rb │ ├── config.ru │ ├── db │ │ ├── migrate │ │ │ ├── 20150213152846_create_messages.rb │ │ │ └── 20150213150625_create_users.rb │ │ └── schema.rb │ ├── Rakefile │ └── README.rdoc ├── support │ └── factory_girl.rb ├── factories │ ├── message.rb │ ├── notification_type.rb │ ├── user.rb │ └── notification.rb ├── models │ ├── user_spec.rb │ ├── message_spec.rb │ ├── concerns │ │ ├── attached_object_spec.rb │ │ └── receiver_spec.rb │ ├── notification_type_spec.rb │ ├── notification_spec.rb │ └── notifier_spec.rb ├── wupee_spec.rb ├── mailers │ └── notifications_mailer_spec.rb ├── controllers │ └── notifications_controller_spec.rb ├── rails_helper.rb └── spec_helper.rb ├── lib ├── tasks │ └── wupee.rake ├── wupee │ ├── version.rb │ ├── engine.rb │ └── notifier.rb ├── generators │ └── wupee │ │ ├── install │ │ ├── templates │ │ │ ├── notifications_mailer.rb │ │ │ └── wupee.rb │ │ ├── USAGE │ │ └── install_generator.rb │ │ └── notification_type │ │ ├── USAGE │ │ └── notification_type_generator.rb └── wupee.rb ├── config └── routes.rb ├── .rspec ├── app ├── views │ └── wupee │ │ └── api │ │ └── notifications │ │ ├── show.json.jbuilder │ │ ├── index.json.jbuilder │ │ └── _notification.json.jbuilder ├── controllers │ └── wupee │ │ ├── application_controller.rb │ │ └── api │ │ └── notifications_controller.rb ├── models │ ├── wupee │ │ ├── notification_type.rb │ │ └── notification.rb │ └── concerns │ │ └── wupee │ │ ├── receiver.rb │ │ └── attached_object.rb └── mailers │ └── wupee │ └── notifications_mailer.rb ├── .gitignore ├── db └── migrate │ ├── 20151029113100_create_wupee_notification_types.rb │ └── 20151029113107_create_wupee_notifications.rb ├── bin └── rails ├── Gemfile ├── Rakefile ├── wupee.gemspec ├── MIT-LICENSE └── README.md /spec/dummy/log/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /spec/dummy/app/mailers/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /spec/dummy/app/models/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /spec/dummy/lib/assets/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /spec/dummy/public/favicon.ico: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /spec/dummy/app/assets/images/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /spec/dummy/app/models/concerns/.keep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /lib/tasks/wupee.rake: -------------------------------------------------------------------------------- 1 | namespace :wupee do 2 | end 3 | -------------------------------------------------------------------------------- /config/routes.rb: -------------------------------------------------------------------------------- 1 | Wupee::Engine.routes.draw do 2 | end 3 | -------------------------------------------------------------------------------- /spec/dummy/app/views/notifications_mailer/abc.html.erb: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /spec/dummy/app/views/notifications/_admin_user_created.html.erb: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /spec/dummy/app/views/notifications/_notify_new_message.html.erb: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /spec/dummy/app/views/wupee/notifications/_notify_new_message.html.erb: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /lib/wupee/version.rb: -------------------------------------------------------------------------------- 1 | module Wupee 2 | VERSION = "2.0.0.beta2" 3 | end 4 | -------------------------------------------------------------------------------- /spec/dummy/app/helpers/application_helper.rb: -------------------------------------------------------------------------------- 1 | module ApplicationHelper 2 | end 3 | -------------------------------------------------------------------------------- /.rspec: -------------------------------------------------------------------------------- 1 | --color 2 | --require spec_helper 3 | --format documentation 4 | --backtrace 5 | -------------------------------------------------------------------------------- /spec/dummy/app/models/user.rb: -------------------------------------------------------------------------------- 1 | class User < ActiveRecord::Base 2 | include Wupee::Receiver 3 | end 4 | -------------------------------------------------------------------------------- /spec/dummy/app/models/message.rb: -------------------------------------------------------------------------------- 1 | class Message < ActiveRecord::Base 2 | include Wupee::AttachedObject 3 | end 4 | -------------------------------------------------------------------------------- /spec/support/factory_girl.rb: -------------------------------------------------------------------------------- 1 | RSpec.configure do |config| 2 | config.include FactoryGirl::Syntax::Methods 3 | end 4 | -------------------------------------------------------------------------------- /spec/dummy/app/views/notifications_mailer/notify_new_message.html.erb: -------------------------------------------------------------------------------- 1 | <%= @locals %> 2 | <%= @subject_interpolations %> 3 | -------------------------------------------------------------------------------- /spec/factories/message.rb: -------------------------------------------------------------------------------- 1 | FactoryGirl.define do 2 | factory :message do 3 | body 'message body' 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /spec/dummy/bin/rake: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require_relative '../config/boot' 3 | require 'rake' 4 | Rake.application.run 5 | -------------------------------------------------------------------------------- /app/views/wupee/api/notifications/show.json.jbuilder: -------------------------------------------------------------------------------- 1 | json.partial! 'wupee/api/notifications/notification', notification: @notification 2 | -------------------------------------------------------------------------------- /app/controllers/wupee/application_controller.rb: -------------------------------------------------------------------------------- 1 | module Wupee 2 | class ApplicationController < ActionController::Base 3 | end 4 | end 5 | -------------------------------------------------------------------------------- /spec/dummy/app/views/wupee/api/notifications/_notify_new_message.json.jbuilder: -------------------------------------------------------------------------------- 1 | json.subject "subject" 2 | json.body "body" 3 | json.url "url" 4 | -------------------------------------------------------------------------------- /spec/models/user_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe User, type: :model do 4 | it_behaves_like "Wupee::Receiver" 5 | end 6 | -------------------------------------------------------------------------------- /app/views/wupee/api/notifications/index.json.jbuilder: -------------------------------------------------------------------------------- 1 | json.array! @notifications, partial: 'wupee/api/notifications/notification', as: :notification 2 | -------------------------------------------------------------------------------- /spec/dummy/app/views/wupee/api/notifications/show.json.jbuilder: -------------------------------------------------------------------------------- 1 | json.partial! 'wupee/api/notifications/notification', notification: @notification 2 | -------------------------------------------------------------------------------- /spec/models/message_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe Message, type: :model do 4 | it_behaves_like "Wupee::AttachedObject" 5 | end 6 | -------------------------------------------------------------------------------- /spec/dummy/app/controllers/notifications_controller.rb: -------------------------------------------------------------------------------- 1 | class NotificationsController < Wupee::Api::NotificationsController 2 | def current_user 3 | end 4 | end -------------------------------------------------------------------------------- /spec/dummy/app/views/wupee/api/notifications/index.json.jbuilder: -------------------------------------------------------------------------------- 1 | json.array! @notifications, partial: 'wupee/api/notifications/notification', as: :notification 2 | -------------------------------------------------------------------------------- /spec/dummy/bin/bundle: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) 3 | load Gem.bin_path('bundler', 'bundle') 4 | -------------------------------------------------------------------------------- /spec/dummy/app/mailers/notifications_mailer.rb: -------------------------------------------------------------------------------- 1 | class NotificationsMailer < Wupee::NotificationsMailer 2 | default from: 'contact@sleede.com' 3 | layout false 4 | end 5 | -------------------------------------------------------------------------------- /spec/dummy/config/locales/en.yml: -------------------------------------------------------------------------------- 1 | en: 2 | wupee: 3 | email_subjects: 4 | notify_new_message: "notify_new_message" 5 | abc: "abc %{a_var_to_interpolate}" 6 | -------------------------------------------------------------------------------- /spec/dummy/bin/rails: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | APP_PATH = File.expand_path('../../config/application', __FILE__) 3 | require_relative '../config/boot' 4 | require 'rails/commands' 5 | -------------------------------------------------------------------------------- /spec/factories/notification_type.rb: -------------------------------------------------------------------------------- 1 | FactoryGirl.define do 2 | factory :notification_type, class: Wupee::NotificationType do 3 | name 'notify_new_message' 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /lib/generators/wupee/install/templates/notifications_mailer.rb: -------------------------------------------------------------------------------- 1 | class NotificationsMailer < Wupee::NotificationsMailer 2 | default from: 'contact@sleede.com' 3 | layout false 4 | end 5 | -------------------------------------------------------------------------------- /spec/dummy/config.ru: -------------------------------------------------------------------------------- 1 | # This file is used by Rack-based servers to start the application. 2 | 3 | require ::File.expand_path('../config/environment', __FILE__) 4 | run Rails.application 5 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/cookies_serializer.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | Rails.application.config.action_dispatch.cookies_serializer = :json 4 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/session_store.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | Rails.application.config.session_store :cookie_store, key: '_dummy_session' 4 | -------------------------------------------------------------------------------- /spec/dummy/config/environment.rb: -------------------------------------------------------------------------------- 1 | # Load the Rails application. 2 | require File.expand_path('../application', __FILE__) 3 | 4 | # Initialize the Rails application. 5 | Rails.application.initialize! 6 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/mime_types.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Add new mime types for use in respond_to blocks: 4 | # Mime::Type.register "text/richtext", :rtf 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .bundle/ 2 | log/*.log 3 | pkg/ 4 | spec/dummy/db/*.sqlite3 5 | spec/dummy/db/*.sqlite3-journal 6 | spec/dummy/log/*.log 7 | spec/dummy/tmp/ 8 | spec/dummy/.sass-cache 9 | Gemfile.lock 10 | .DS_Store 11 | 12 | wupee-*.gem -------------------------------------------------------------------------------- /spec/dummy/config/routes.rb: -------------------------------------------------------------------------------- 1 | Rails.application.routes.draw do 2 | resources :notifications, only: [:index, :show], defaults: { format: :json } do 3 | patch :mark_as_read, on: :member 4 | patch :mark_all_as_read, on: :collection 5 | end 6 | end 7 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/filter_parameter_logging.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Configure sensitive parameters which will be filtered from the log file. 4 | Rails.application.config.filter_parameters += [:password] 5 | -------------------------------------------------------------------------------- /spec/dummy/db/migrate/20150213152846_create_messages.rb: -------------------------------------------------------------------------------- 1 | class CreateMessages < ActiveRecord::Migration 2 | def change 3 | create_table :messages do |t| 4 | t.string :body 5 | 6 | t.timestamps null: false 7 | end 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /app/models/wupee/notification_type.rb: -------------------------------------------------------------------------------- 1 | class Wupee::NotificationType < ActiveRecord::Base 2 | validates :name, presence: true 3 | validates :name, uniqueness: true 4 | 5 | has_many :notifications, foreign_key: :notification_type_id, dependent: :destroy 6 | end 7 | -------------------------------------------------------------------------------- /spec/dummy/app/controllers/application_controller.rb: -------------------------------------------------------------------------------- 1 | class ApplicationController < ActionController::Base 2 | # Prevent CSRF attacks by raising an exception. 3 | # For APIs, you may want to use :null_session instead. 4 | protect_from_forgery with: :exception 5 | end 6 | -------------------------------------------------------------------------------- /app/models/concerns/wupee/receiver.rb: -------------------------------------------------------------------------------- 1 | module Wupee 2 | module Receiver 3 | extend ActiveSupport::Concern 4 | 5 | included do 6 | has_many :notifications, as: :receiver, dependent: :destroy, class_name: "Wupee::Notification" 7 | end 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /spec/dummy/config/boot.rb: -------------------------------------------------------------------------------- 1 | # Set up gems listed in the Gemfile. 2 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../../../Gemfile', __FILE__) 3 | 4 | require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE']) 5 | $LOAD_PATH.unshift File.expand_path('../../../../lib', __FILE__) 6 | -------------------------------------------------------------------------------- /spec/dummy/db/migrate/20150213150625_create_users.rb: -------------------------------------------------------------------------------- 1 | class CreateUsers < ActiveRecord::Migration 2 | def change 3 | create_table :users do |t| 4 | t.string :name 5 | t.string :email 6 | 7 | t.timestamps null: false 8 | end 9 | end 10 | end 11 | -------------------------------------------------------------------------------- /spec/factories/user.rb: -------------------------------------------------------------------------------- 1 | FactoryGirl.define do 2 | sequence(:email) { |n| "user#{n}@sleede.com" } 3 | sequence(:name) { |n| "user#{n}" } 4 | 5 | factory :user do 6 | email { FactoryGirl.generate :email } 7 | name { FactoryGirl.generate :name } 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /spec/dummy/Rakefile: -------------------------------------------------------------------------------- 1 | # Add your own tasks in files placed in lib/tasks ending in .rake, 2 | # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. 3 | 4 | require File.expand_path('../config/application', __FILE__) 5 | 6 | Rails.application.load_tasks 7 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/wupee.rb: -------------------------------------------------------------------------------- 1 | Wupee.mailer = NotificationsMailer 2 | Wupee.deliver_when = :now 3 | 4 | Wupee.email_sending_rule = Proc.new do |receiver, notification_type| 5 | true 6 | end 7 | 8 | Wupee.notification_sending_rule = Proc.new do |receiver, notification_type| 9 | true 10 | end -------------------------------------------------------------------------------- /app/models/concerns/wupee/attached_object.rb: -------------------------------------------------------------------------------- 1 | module Wupee 2 | module AttachedObject 3 | extend ActiveSupport::Concern 4 | 5 | included do 6 | has_many :notifications_as_attached_object, as: :attached_object, dependent: :destroy, class_name: "Wupee::Notification" 7 | end 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /app/views/wupee/api/notifications/_notification.json.jbuilder: -------------------------------------------------------------------------------- 1 | json.extract! notification, :id, :notification_type_id, :created_at, :is_read 2 | json.attached_object notification.attached_object 3 | json.message do 4 | json.partial! "wupee/api/notifications/#{notification.notification_type.name}", notification: notification 5 | end 6 | -------------------------------------------------------------------------------- /spec/dummy/app/views/wupee/api/notifications/_notification.json.jbuilder: -------------------------------------------------------------------------------- 1 | json.extract! notification, :id, :notification_type_id, :created_at, :is_read 2 | json.attached_object notification.attached_object 3 | json.message do 4 | json.partial! "wupee/api/notifications/#{notification.notification_type.name}", notification: notification 5 | end 6 | -------------------------------------------------------------------------------- /db/migrate/20151029113100_create_wupee_notification_types.rb: -------------------------------------------------------------------------------- 1 | class CreateWupeeNotificationTypes < ActiveRecord::Migration 2 | def change 3 | create_table :wupee_notification_types do |t| 4 | t.string :name 5 | t.timestamps null: false 6 | end 7 | 8 | add_index :wupee_notification_types, :name, unique: true 9 | end 10 | end 11 | -------------------------------------------------------------------------------- /lib/wupee/engine.rb: -------------------------------------------------------------------------------- 1 | module Wupee 2 | class Engine < ::Rails::Engine 3 | isolate_namespace Wupee 4 | 5 | config.generators do |g| 6 | g.test_framework :rspec, fixture: false 7 | g.fixture_replacement :factory_girl, dir: 'spec/factories' 8 | g.assets false 9 | g.helper false 10 | end 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /spec/factories/notification.rb: -------------------------------------------------------------------------------- 1 | FactoryGirl.define do 2 | factory :notification, class: Wupee::Notification do 3 | association :receiver, factory: :user, strategy: :create 4 | association :attached_object, factory: :message, strategy: :create 5 | notification_type { Wupee::NotificationType.find_or_create_by(name: 'notify_new_message') } 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /lib/wupee.rb: -------------------------------------------------------------------------------- 1 | require "wupee/engine" 2 | require "wupee/notifier" 3 | 4 | module Wupee 5 | mattr_accessor :mailer, :deliver_when, :email_sending_rule, :notification_sending_rule 6 | 7 | def self.notify(opts = {}, &block) 8 | wupee_notifier = Wupee::Notifier.new(opts) 9 | yield wupee_notifier if block_given? 10 | wupee_notifier.execute 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /spec/wupee_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | 3 | describe Wupee do 4 | it "has a setter for mailer" do 5 | expect(Wupee).to respond_to(:mailer=).with(1).argument 6 | end 7 | 8 | it "has a getter for mailer" do 9 | expect(Wupee).to respond_to(:mailer) 10 | end 11 | 12 | it "has method notify" do 13 | expect(Wupee).to respond_to(:notify) 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /lib/generators/wupee/notification_type/USAGE: -------------------------------------------------------------------------------- 1 | Description: 2 | Add a notification by name 3 | 4 | Example: 5 | rails generate notification name 6 | 7 | This will create or modify: 8 | insert app/models/notification_type.rb 9 | create app/views/notifications_mailer/name.html.erb 10 | insert app/mailers/notifications_mailer.rb 11 | insert config/locales/en.yml 12 | -------------------------------------------------------------------------------- /spec/dummy/app/views/layouts/application.html.erb: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Dummy 5 | <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %> 6 | <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %> 7 | <%= csrf_meta_tags %> 8 | 9 | 10 | 11 | <%= yield %> 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /spec/models/concerns/attached_object_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | shared_examples_for "Wupee::AttachedObject" do 4 | let(:model) { described_class } 5 | 6 | it "destroys notification on destroy" do 7 | attached_object = create model.name.underscore 8 | notif = create :notification, attached_object: attached_object 9 | expect { attached_object.destroy }.to change { Wupee::Notification.count }.by(-1) 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/backtrace_silencers.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. 4 | # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } 5 | 6 | # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. 7 | # Rails.backtrace_cleaner.remove_silencers! 8 | -------------------------------------------------------------------------------- /lib/generators/wupee/install/USAGE: -------------------------------------------------------------------------------- 1 | Description: 2 | Generates model notification and notification_type, a mailer, an initializer 3 | 4 | Example: 5 | rails generate wupee:install 6 | 7 | This will create: 8 | db/migrate/created_notifcation.rb 9 | app/models/notification.rb 10 | app/models/notification_type.rb 11 | app/mailers/notifications_mailer.rb 12 | config/initializers/wupee.rb 13 | 14 | this will update: 15 | config/locales/{local}.yml 16 | -------------------------------------------------------------------------------- /spec/models/concerns/receiver_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | shared_examples_for "Wupee::Receiver" do 4 | let(:model) { described_class } 5 | 6 | it "has many notifications" do 7 | expect(model.new).to respond_to(:notifications) 8 | end 9 | 10 | it "destroys notification on destroy" do 11 | receiver = create model.name.underscore 12 | create :notification, receiver: receiver 13 | expect { receiver.destroy }.to change { Wupee::Notification.count }.by(-1) 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /bin/rails: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # This command will automatically be run when you run "rails" with Rails 4 gems installed from the root of your application. 3 | 4 | ENGINE_ROOT = File.expand_path('../..', __FILE__) 5 | ENGINE_PATH = File.expand_path('../../lib/wupee/engine', __FILE__) 6 | 7 | # Set up gems listed in the Gemfile. 8 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) 9 | require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE']) 10 | 11 | require 'rails/all' 12 | require 'rails/engine/commands' 13 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/assets.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Version of your assets, change this if you want to expire all your assets. 4 | Rails.application.config.assets.version = '1.0' 5 | 6 | # Add additional assets to the asset load path 7 | # Rails.application.config.assets.paths << Emoji.images_path 8 | 9 | # Precompile additional assets. 10 | # application.js, application.css, and all non-JS/CSS in app/assets folder are already added. 11 | # Rails.application.config.assets.precompile += %w( search.js ) 12 | -------------------------------------------------------------------------------- /lib/generators/wupee/install/install_generator.rb: -------------------------------------------------------------------------------- 1 | class Wupee::InstallGenerator < Rails::Generators::Base 2 | source_root File.expand_path('../templates', __FILE__) 3 | 4 | def copy_notifications_mailer 5 | template "notifications_mailer.rb", "app/mailers/notifications_mailer.rb" 6 | end 7 | 8 | def copy_initializer 9 | template "wupee.rb", "config/initializers/wupee.rb" 10 | end 11 | 12 | def add_subject_locale 13 | append_file "config/locales/#{I18n.locale.to_s}.yml" do 14 | <<-CODE 15 | wupee: 16 | email_subjects: 17 | CODE 18 | end 19 | end 20 | end 21 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | 3 | # Declare your gem's dependencies in wupee.gemspec. 4 | # Bundler will treat runtime dependencies like base dependencies, and 5 | # development dependencies will be added by default to the :development group. 6 | gemspec 7 | 8 | # Declare any dependencies that are still in development here instead of in 9 | # your gemspec. These might include edge Rails or gems from your path or 10 | # Git. Remember to move these dependencies to your gemspec before releasing 11 | # your gem to rubygems.org. 12 | 13 | # To use a debugger 14 | # gem 'byebug', group: [:development, :test] 15 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/wrap_parameters.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # This file contains settings for ActionController::ParamsWrapper which 4 | # is enabled by default. 5 | 6 | # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. 7 | ActiveSupport.on_load(:action_controller) do 8 | wrap_parameters format: [:json] if respond_to?(:wrap_parameters) 9 | end 10 | 11 | # To enable root element in JSON for ActiveRecord objects. 12 | # ActiveSupport.on_load(:active_record) do 13 | # self.include_root_in_json = true 14 | # end 15 | -------------------------------------------------------------------------------- /spec/dummy/README.rdoc: -------------------------------------------------------------------------------- 1 | == README 2 | 3 | This README would normally document whatever steps are necessary to get the 4 | application up and running. 5 | 6 | Things you may want to cover: 7 | 8 | * Ruby version 9 | 10 | * System dependencies 11 | 12 | * Configuration 13 | 14 | * Database creation 15 | 16 | * Database initialization 17 | 18 | * How to run the test suite 19 | 20 | * Services (job queues, cache servers, search engines, etc.) 21 | 22 | * Deployment instructions 23 | 24 | * ... 25 | 26 | 27 | Please feel free to use a different markup language if you do not plan to run 28 | rake doc:app. 29 | -------------------------------------------------------------------------------- /spec/dummy/config/database.yml: -------------------------------------------------------------------------------- 1 | # SQLite version 3.x 2 | # gem install sqlite3 3 | # 4 | # Ensure the SQLite 3 gem is defined in your Gemfile 5 | # gem 'sqlite3' 6 | # 7 | default: &default 8 | adapter: sqlite3 9 | pool: 5 10 | timeout: 5000 11 | 12 | development: 13 | <<: *default 14 | database: db/development.sqlite3 15 | 16 | # Warning: The database defined as "test" will be erased and 17 | # re-generated from your development database when you run "rake". 18 | # Do not set this db to the same as development or production. 19 | test: 20 | <<: *default 21 | database: db/test.sqlite3 22 | 23 | production: 24 | <<: *default 25 | database: db/production.sqlite3 26 | -------------------------------------------------------------------------------- /spec/dummy/app/assets/javascripts/application.js: -------------------------------------------------------------------------------- 1 | // This is a manifest file that'll be compiled into application.js, which will include all the files 2 | // listed below. 3 | // 4 | // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, 5 | // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. 6 | // 7 | // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the 8 | // compiled file. 9 | // 10 | // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details 11 | // about supported directives. 12 | // 13 | //= require_tree . 14 | -------------------------------------------------------------------------------- /lib/generators/wupee/install/templates/wupee.rb: -------------------------------------------------------------------------------- 1 | Wupee.mailer = NotificationsMailer 2 | Wupee.deliver_when = :now 3 | 4 | # uncomment and implement your logic here to avoid/permit email sending to your users 5 | # leave it commented if you always want your users received emails 6 | # Wupee.email_sending_rule = Proc.new do |receiver, notification_type| 7 | # # logic goes here, returning a boolean 8 | # end 9 | 10 | # uncomment and implement your logic here to avoid/permit email sending to your users 11 | # leave it commented if you always want your users received notifications 12 | # Wupee.notification_sending_rule = Proc.new do |receiver, notification_type| 13 | # # logic goes here, returning a boolean 14 | # end -------------------------------------------------------------------------------- /spec/dummy/config/initializers/inflections.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Add new inflection rules using the following format. Inflections 4 | # are locale specific, and you may define rules for as many different 5 | # locales as you wish. All of these examples are active by default: 6 | # ActiveSupport::Inflector.inflections(:en) do |inflect| 7 | # inflect.plural /^(ox)$/i, '\1en' 8 | # inflect.singular /^(ox)en/i, '\1' 9 | # inflect.irregular 'person', 'people' 10 | # inflect.uncountable %w( fish sheep ) 11 | # end 12 | 13 | # These inflection rules are supported but not enabled by default: 14 | # ActiveSupport::Inflector.inflections(:en) do |inflect| 15 | # inflect.acronym 'RESTful' 16 | # end 17 | -------------------------------------------------------------------------------- /app/models/wupee/notification.rb: -------------------------------------------------------------------------------- 1 | class Wupee::Notification < ActiveRecord::Base 2 | belongs_to :receiver, polymorphic: true 3 | belongs_to :attached_object, polymorphic: true 4 | belongs_to :notification_type, class_name: "Wupee::NotificationType" 5 | 6 | validates :receiver, presence: true 7 | validates :notification_type, presence: true 8 | 9 | scope :read, -> { where(is_read: true) } 10 | scope :unread, -> { where(is_read: false) } 11 | scope :wanted, -> { where(is_wanted: true) } 12 | scope :unwanted, -> { where(is_wanted: false) } 13 | scope :ordered, -> { order(created_at: :desc) } 14 | 15 | def mark_as_read 16 | update_columns(is_read: true) 17 | end 18 | 19 | def mark_as_sent 20 | update_columns(is_sent: true) 21 | end 22 | end 23 | -------------------------------------------------------------------------------- /spec/dummy/app/assets/stylesheets/application.css: -------------------------------------------------------------------------------- 1 | /* 2 | * This is a manifest file that'll be compiled into application.css, which will include all the files 3 | * listed below. 4 | * 5 | * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets, 6 | * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path. 7 | * 8 | * You're free to add application-wide styles to this file and they'll appear at the bottom of the 9 | * compiled file so the styles you add here take precedence over styles defined in any styles 10 | * defined in the other CSS/SCSS files in this directory. It is generally better to create a new 11 | * file per style scope. 12 | * 13 | *= require_tree . 14 | *= require_self 15 | */ 16 | -------------------------------------------------------------------------------- /lib/generators/wupee/notification_type/notification_type_generator.rb: -------------------------------------------------------------------------------- 1 | class Wupee::NotificationTypeGenerator < Rails::Generators::NamedBase 2 | def add_notification_subject 3 | inject_into_file "config/locales/#{I18n.locale.to_s}.yml", after: /email_subjects:\n/ do 4 | <<-CODE 5 | #{file_name}: "#{file_name}" 6 | CODE 7 | end 8 | end 9 | 10 | def create_notification_json_template_file 11 | create_file "app/views/wupee/api/notifications/_#{file_name}.json.jbuilder", <<-FILE 12 | json.subject "subject" 13 | json.body "body" 14 | json.url "url" 15 | FILE 16 | end 17 | 18 | def create_notification_html_template_file 19 | create_file "app/views/wupee/notifications/_#{file_name}.html.erb", <<-FILE 20 | FILE 21 | end 22 | 23 | def create_notification_type_object 24 | Wupee::NotificationType.create!(name: file_name) 25 | end 26 | end 27 | -------------------------------------------------------------------------------- /db/migrate/20151029113107_create_wupee_notifications.rb: -------------------------------------------------------------------------------- 1 | class CreateWupeeNotifications < ActiveRecord::Migration 2 | def change 3 | create_table :wupee_notifications do |t| 4 | t.references :receiver, polymorphic: true, index: { name: 'idx_wupee_notifications_on_receiver_id' } 5 | t.references :attached_object, polymorphic: true, index: { name: 'idx_wupee_notifications_on_attached_object_id' } 6 | t.integer :notification_type_id 7 | t.boolean :is_read, default: false 8 | t.boolean :is_sent, default: false 9 | t.boolean :is_wanted, default: true 10 | 11 | t.timestamps null: false 12 | end 13 | 14 | add_index :wupee_notifications, :notification_type_id, name: 'idx_wupee_notifications_on_notification_type_id' 15 | add_foreign_key :wupee_notifications, :wupee_notification_types, column: :notification_type_id 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | begin 2 | require 'bundler/setup' 3 | rescue LoadError 4 | puts 'You must `gem install bundler` and `bundle install` to run rake tasks' 5 | end 6 | 7 | require 'rdoc/task' 8 | 9 | RDoc::Task.new(:rdoc) do |rdoc| 10 | rdoc.rdoc_dir = 'rdoc' 11 | rdoc.title = 'Wupee' 12 | rdoc.options << '--line-numbers' 13 | rdoc.rdoc_files.include('README.rdoc') 14 | rdoc.rdoc_files.include('lib/**/*.rb') 15 | end 16 | 17 | APP_RAKEFILE = File.expand_path("../spec/dummy/Rakefile", __FILE__) 18 | load 'rails/tasks/engine.rake' 19 | 20 | Bundler::GemHelper.install_tasks 21 | 22 | Dir[File.join(File.dirname(__FILE__), 'tasks/**/*.rake')].each {|f| load f } 23 | 24 | require 'rspec/core' 25 | require 'rspec/core/rake_task' 26 | 27 | desc "Run all specs in spec directory (excluding plugin specs)" 28 | RSpec::Core::RakeTask.new(:spec => 'app:db:test:prepare') 29 | 30 | task :default => :spec 31 | -------------------------------------------------------------------------------- /spec/dummy/bin/setup: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require 'pathname' 3 | 4 | # path to your application root. 5 | APP_ROOT = Pathname.new File.expand_path('../../', __FILE__) 6 | 7 | Dir.chdir APP_ROOT do 8 | # This script is a starting point to setup your application. 9 | # Add necessary setup steps to this file: 10 | 11 | puts "== Installing dependencies ==" 12 | system "gem install bundler --conservative" 13 | system "bundle check || bundle install" 14 | 15 | # puts "\n== Copying sample files ==" 16 | # unless File.exist?("config/database.yml") 17 | # system "cp config/database.yml.sample config/database.yml" 18 | # end 19 | 20 | puts "\n== Preparing database ==" 21 | system "bin/rake db:setup" 22 | 23 | puts "\n== Removing old logs and tempfiles ==" 24 | system "rm -f log/*" 25 | system "rm -rf tmp/cache" 26 | 27 | puts "\n== Restarting application server ==" 28 | system "touch tmp/restart.txt" 29 | end 30 | -------------------------------------------------------------------------------- /app/controllers/wupee/api/notifications_controller.rb: -------------------------------------------------------------------------------- 1 | module Wupee 2 | class Api::NotificationsController < ApplicationController 3 | def index 4 | scopes = params[:scopes].present? ? params[:scopes].split(',') : [] 5 | scopes = ['read', 'unread', 'wanted', 'unwanted', 'ordered'] & scopes 6 | 7 | @notifications = current_user.notifications 8 | 9 | scopes.each do |scope| 10 | @notifications = @notifications.public_send(scope) 11 | end 12 | end 13 | 14 | def show 15 | @notification = find_notification 16 | end 17 | 18 | def mark_as_read 19 | @notification = find_notification 20 | @notification.mark_as_read 21 | render :show 22 | end 23 | 24 | def mark_all_as_read 25 | current_user.notifications.unread.update_all(is_read: true) 26 | head :no_content 27 | end 28 | 29 | private 30 | def find_notification 31 | current_user.notifications.find(params[:id]) 32 | end 33 | end 34 | end 35 | -------------------------------------------------------------------------------- /wupee.gemspec: -------------------------------------------------------------------------------- 1 | $:.push File.expand_path("../lib", __FILE__) 2 | 3 | # Maintain your gem's version: 4 | require "wupee/version" 5 | 6 | # Describe your gem and declare its dependencies: 7 | Gem::Specification.new do |s| 8 | s.name = "wupee" 9 | s.version = Wupee::VERSION 10 | s.authors = ["Peng DU", "Nicolas Florentin"] 11 | s.email = ["peng@sleede.com", "nicolas@sleede.com"] 12 | s.homepage = "https://github.com/sleede/wupee" 13 | s.summary = "Simple notification system for rails" 14 | s.description = "Simple notification system for rails" 15 | s.license = "MIT" 16 | 17 | s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"] 18 | s.test_files = Dir["spec/**/*"] 19 | 20 | s.add_dependency "rails", '>= 4.2.0' 21 | #s.add_dependency "responders", "~> 2.0" 22 | s.add_dependency "jbuilder", "~> 2.0" 23 | 24 | s.add_development_dependency "sqlite3" 25 | s.add_development_dependency "rspec-rails" 26 | s.add_development_dependency "factory_girl_rails" 27 | end 28 | -------------------------------------------------------------------------------- /spec/dummy/config/secrets.yml: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Your secret key is used for verifying the integrity of signed cookies. 4 | # If you change this key, all old signed cookies will become invalid! 5 | 6 | # Make sure the secret is at least 30 characters and all random, 7 | # no regular words or you'll be exposed to dictionary attacks. 8 | # You can use `rake secret` to generate a secure secret key. 9 | 10 | # Make sure the secrets in this file are kept private 11 | # if you're sharing your code publicly. 12 | 13 | development: 14 | secret_key_base: bac8f84c30b469b26411ccff2193e1e2f940db7a4206834ee8c7cab76886d6c0e7db724ea843f84060617b032bfb4000f2b5d0ee55ded5549ad3fcaf44cdd8cc 15 | 16 | test: 17 | secret_key_base: d1fd44cc278480713531412b07c834d46b63b25fb7a1fc48fd7a33c5d176f6a1c929189d143b6fd4a3bfcde8a930a784b319243fab188ac13791bc943c3873d4 18 | 19 | # Do not keep production secrets in the repository, 20 | # instead read values from the environment. 21 | production: 22 | secret_key_base: <%= ENV["SECRET_KEY_BASE"] %> 23 | -------------------------------------------------------------------------------- /MIT-LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2015 Peng DU 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining 4 | a copy of this software and associated documentation files (the 5 | "Software"), to deal in the Software without restriction, including 6 | without limitation the rights to use, copy, modify, merge, publish, 7 | distribute, sublicense, and/or sell copies of the Software, and to 8 | permit persons to whom the Software is furnished to do so, subject to 9 | the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be 12 | included in all copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 15 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 16 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 17 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 18 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 19 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 20 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /spec/mailers/notifications_mailer_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe NotificationsMailer do 4 | subject { NotificationsMailer } 5 | let!(:notification_type) { create :notification_type, name: "abc" } 6 | let!(:notification) { create :notification, notification_type: notification_type } 7 | 8 | it 'should respond to method #send_mail_for' do 9 | expect(subject).to respond_to(:send_mail_for) 10 | end 11 | 12 | describe 'send mail by a notification' do 13 | before do 14 | @mail = subject.send_mail_for(notification, a_var_to_interpolate: "hello world").deliver_now 15 | end 16 | 17 | it 'should be sent' do 18 | expect(ActionMailer::Base.deliveries).not_to be_empty 19 | end 20 | 21 | it 'should have the correct subject' do 22 | expect(@mail.subject).to eq I18n.t(".wupee.email_subjects.#{notification.notification_type.name}", a_var_to_interpolate: "hello world") 23 | end 24 | 25 | it 'should have correct receiver' do 26 | expect(@mail.to).to eq [notification.receiver.email] 27 | end 28 | 29 | it 'should mark notification as sent' do 30 | expect(notification.is_sent).to eq true 31 | end 32 | end 33 | end 34 | -------------------------------------------------------------------------------- /spec/models/notification_type_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe Wupee::NotificationType, type: :model do 4 | let!(:receiver) { create :user } 5 | let!(:notification_type_name) { 'notify_new_message' } 6 | let!(:notification_type) { create :notification_type, name: notification_type_name } 7 | let!(:notification) { create :notification, notification_type: notification_type, receiver: receiver } 8 | 9 | context "validations" do 10 | it "validates presence of name" do 11 | notification_type = Wupee::NotificationType.new 12 | notification_type.valid? 13 | expect(notification_type.errors).to have_key :name 14 | end 15 | 16 | it "validates presence of uniqueness of name" do 17 | notification_type = Wupee::NotificationType.new(name: notification_type_name) 18 | notification_type.valid? 19 | expect(notification_type.errors).to have_key :name 20 | end 21 | end 22 | 23 | context "methods" do 24 | it "responds to notifications" do 25 | expect(notification_type).to respond_to(:notifications) 26 | end 27 | end 28 | 29 | context "associations" do 30 | it "destroys notifications on destroy" do 31 | expect { notification_type.destroy! }.to change { Wupee::Notification.count }.by(-1) 32 | end 33 | end 34 | end 35 | -------------------------------------------------------------------------------- /app/mailers/wupee/notifications_mailer.rb: -------------------------------------------------------------------------------- 1 | module Wupee 2 | class NotificationsMailer < ActionMailer::Base 3 | after_action :mark_notification_as_sent 4 | 5 | def send_mail_for(notification, subject_interpolations = {}, locals_interpolations = {}, headers = {}) 6 | @notification = notification 7 | @receiver = notification.receiver 8 | @attached_object = notification.attached_object 9 | @subject_interpolations = subject_interpolations 10 | @locals = locals_interpolations 11 | @headers = headers 12 | 13 | if !respond_to?(notification.notification_type.name) 14 | class_eval %Q{ 15 | def #{notification.notification_type.name} 16 | mail_args = { 17 | to: @receiver.email, 18 | subject: t('wupee.email_subjects.#{notification.notification_type.name}', **@subject_interpolations), 19 | template_name: '#{notification.notification_type.name}', 20 | content_type: 'text/html' 21 | } 22 | 23 | mail_args = mail_args.merge(@headers) 24 | mail mail_args 25 | end 26 | } 27 | end 28 | 29 | send(notification.notification_type.name) 30 | end 31 | 32 | private 33 | def mark_notification_as_sent 34 | @notification.mark_as_sent unless @notification.is_sent 35 | end 36 | end 37 | end 38 | -------------------------------------------------------------------------------- /spec/models/notification_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe Wupee::Notification, type: :model do 4 | let!(:message) { create :message } 5 | let!(:receiver) { create :user } 6 | let!(:notification_type_name) { 'notify_new_message' } 7 | let!(:notification_type) { create :notification_type, name: notification_type_name } 8 | 9 | context "validations" do 10 | it "validates presence of receiver" do 11 | notification = Wupee::Notification.new 12 | notification.valid? 13 | expect(notification.errors).to have_key :receiver 14 | end 15 | 16 | it "validates presence of notification_type" do 17 | notification = Wupee::Notification.new 18 | notification.valid? 19 | expect(notification.errors).to have_key :notification_type 20 | end 21 | end 22 | 23 | it 'should be able to be marked as read' do 24 | notification = create :notification 25 | notification.mark_as_read 26 | expect(notification.is_read).to eq true 27 | end 28 | 29 | it 'should be able to be marked as sent' do 30 | notification = create :notification 31 | notification.mark_as_sent 32 | expect(notification.is_sent).to eq true 33 | end 34 | 35 | context "default values" do 36 | it { expect(create(:notification).is_read).to be false } 37 | it { expect(create(:notification).is_sent).to be false } 38 | end 39 | end 40 | -------------------------------------------------------------------------------- /spec/dummy/config/application.rb: -------------------------------------------------------------------------------- 1 | require File.expand_path('../boot', __FILE__) 2 | 3 | # Pick the frameworks you want: 4 | require "active_record/railtie" 5 | require "action_controller/railtie" 6 | require "action_mailer/railtie" 7 | require "action_view/railtie" 8 | require "sprockets/railtie" 9 | require "jbuilder" 10 | # require "rails/test_unit/railtie" 11 | 12 | Bundler.require(*Rails.groups) 13 | require "wupee" 14 | 15 | module Dummy 16 | class Application < Rails::Application 17 | # Settings in config/environments/* take precedence over those specified here. 18 | # Application configuration should go into files in config/initializers 19 | # -- all .rb files in that directory are automatically loaded. 20 | 21 | # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. 22 | # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. 23 | # config.time_zone = 'Central Time (US & Canada)' 24 | 25 | # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. 26 | # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] 27 | # config.i18n.default_locale = :de 28 | 29 | # Do not swallow errors in after_commit/after_rollback callbacks. 30 | config.active_record.raise_in_transactional_callbacks = true 31 | end 32 | end 33 | -------------------------------------------------------------------------------- /spec/dummy/public/500.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | We're sorry, but something went wrong (500) 5 | 6 | 55 | 56 | 57 | 58 | 59 |
60 |
61 |

We're sorry, but something went wrong.

62 |
63 |

If you are the application owner check the logs for more information.

64 |
65 | 66 | 67 | -------------------------------------------------------------------------------- /spec/dummy/config/environments/development.rb: -------------------------------------------------------------------------------- 1 | Rails.application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb. 3 | 4 | # In the development environment your application's code is reloaded on 5 | # every request. This slows down response time but is perfect for development 6 | # since you don't have to restart the web server when you make code changes. 7 | config.cache_classes = false 8 | 9 | # Do not eager load code on boot. 10 | config.eager_load = false 11 | 12 | # Show full error reports and disable caching. 13 | config.consider_all_requests_local = true 14 | config.action_controller.perform_caching = false 15 | 16 | # Don't care if the mailer can't send. 17 | config.action_mailer.raise_delivery_errors = false 18 | 19 | # Print deprecation notices to the Rails logger. 20 | config.active_support.deprecation = :log 21 | 22 | # Raise an error on page load if there are pending migrations. 23 | config.active_record.migration_error = :page_load 24 | 25 | # Debug mode disables concatenation and preprocessing of assets. 26 | # This option may cause significant delays in view rendering with a large 27 | # number of complex assets. 28 | config.assets.debug = true 29 | 30 | # Asset digests allow you to set far-future HTTP expiration dates on all assets, 31 | # yet still be able to expire them through the digest params. 32 | config.assets.digest = true 33 | 34 | # Adds additional error checking when serving assets at runtime. 35 | # Checks for improperly declared sprockets dependencies. 36 | # Raises helpful error messages. 37 | config.assets.raise_runtime_errors = true 38 | 39 | # Raises error for missing translations 40 | # config.action_view.raise_on_missing_translations = true 41 | end 42 | -------------------------------------------------------------------------------- /spec/dummy/public/422.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | The change you wanted was rejected (422) 5 | 6 | 55 | 56 | 57 | 58 | 59 |
60 |
61 |

The change you wanted was rejected.

62 |

Maybe you tried to change something you didn't have access to.

63 |
64 |

If you are the application owner check the logs for more information.

65 |
66 | 67 | 68 | -------------------------------------------------------------------------------- /spec/dummy/public/404.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | The page you were looking for doesn't exist (404) 5 | 6 | 55 | 56 | 57 | 58 | 59 |
60 |
61 |

The page you were looking for doesn't exist.

62 |

You may have mistyped the address or the page may have moved.

63 |
64 |

If you are the application owner check the logs for more information.

65 |
66 | 67 | 68 | -------------------------------------------------------------------------------- /spec/controllers/notifications_controller_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | RSpec.describe NotificationsController, type: :controller do 4 | let(:notification) { create :notification } 5 | 6 | before :each do 7 | allow_any_instance_of(NotificationsController).to receive(:current_user).and_return(notification.receiver) 8 | end 9 | 10 | it 'should get current user' do 11 | expect(subject).to receive(:current_user).and_return(notification.receiver) 12 | get :index, format: :json 13 | end 14 | 15 | describe 'GET index json' do 16 | render_views 17 | 18 | it "should returns a notification from a rendered template" do 19 | get :index, format: :json 20 | expect(json.size).to eq 1 21 | expect(json[0]['id']).to eq notification.id 22 | expect(json[0]['message']['subject']).to eq "subject" 23 | end 24 | 25 | it "should accept scopes as param" do 26 | get :index, format: :json, scopes: "unwanted" 27 | expect(json.size).to eq 0 28 | end 29 | end 30 | 31 | describe 'GET show json' do 32 | render_views 33 | 34 | it "should returns a notification from a rendered template" do 35 | get :show, format: :json, id: notification.id 36 | expect(json['id']).to eq notification.id 37 | expect(json['message']['subject']).to eq "subject" 38 | end 39 | end 40 | 41 | describe 'PUT update' do 42 | render_views 43 | 44 | it "should mark as read" do 45 | patch :mark_as_read, id: notification.id, format: :json 46 | expect(json['is_read']).to eq true 47 | end 48 | end 49 | 50 | describe 'PUT update_all' do 51 | render_views 52 | 53 | it "should all notification of user mark as read" do 54 | patch :mark_all_as_read, format: :json 55 | expect(notification.reload.is_read).to eq true 56 | end 57 | end 58 | 59 | def json 60 | ActiveSupport::JSON.decode(response.body) 61 | end 62 | end 63 | -------------------------------------------------------------------------------- /spec/dummy/config/environments/test.rb: -------------------------------------------------------------------------------- 1 | Rails.application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb. 3 | 4 | # The test environment is used exclusively to run your application's 5 | # test suite. You never need to work with it otherwise. Remember that 6 | # your test database is "scratch space" for the test suite and is wiped 7 | # and recreated between test runs. Don't rely on the data there! 8 | config.cache_classes = true 9 | 10 | # Do not eager load code on boot. This avoids loading your whole application 11 | # just for the purpose of running a single test. If you are using a tool that 12 | # preloads Rails for running tests, you may have to set it to true. 13 | config.eager_load = false 14 | 15 | # Configure static file server for tests with Cache-Control for performance. 16 | config.serve_static_files = true 17 | config.static_cache_control = 'public, max-age=3600' 18 | 19 | # Show full error reports and disable caching. 20 | config.consider_all_requests_local = true 21 | config.action_controller.perform_caching = false 22 | 23 | # Raise exceptions instead of rendering exception templates. 24 | config.action_dispatch.show_exceptions = false 25 | 26 | # Disable request forgery protection in test environment. 27 | config.action_controller.allow_forgery_protection = false 28 | 29 | # Tell Action Mailer not to deliver emails to the real world. 30 | # The :test delivery method accumulates sent emails in the 31 | # ActionMailer::Base.deliveries array. 32 | config.action_mailer.delivery_method = :test 33 | 34 | # Randomize the order test cases are executed. 35 | config.active_support.test_order = :random 36 | 37 | # Print deprecation notices to the stderr. 38 | config.active_support.deprecation = :stderr 39 | 40 | # Raises error for missing translations 41 | # config.action_view.raise_on_missing_translations = true 42 | end 43 | -------------------------------------------------------------------------------- /spec/dummy/db/schema.rb: -------------------------------------------------------------------------------- 1 | # encoding: UTF-8 2 | # This file is auto-generated from the current state of the database. Instead 3 | # of editing this file, please use the migrations feature of Active Record to 4 | # incrementally modify your database, and then regenerate this schema definition. 5 | # 6 | # Note that this schema.rb definition is the authoritative source for your 7 | # database schema. If you need to create the application database on another 8 | # system, you should be using db:schema:load, not running all the migrations 9 | # from scratch. The latter is a flawed and unsustainable approach (the more migrations 10 | # you'll amass, the slower it'll run and the greater likelihood for issues). 11 | # 12 | # It's strongly recommended that you check this file into your version control system. 13 | 14 | ActiveRecord::Schema.define(version: 20151029113107) do 15 | 16 | create_table "messages", force: :cascade do |t| 17 | t.string "body" 18 | t.datetime "created_at", null: false 19 | t.datetime "updated_at", null: false 20 | end 21 | 22 | create_table "users", force: :cascade do |t| 23 | t.string "name" 24 | t.string "email" 25 | t.datetime "created_at", null: false 26 | t.datetime "updated_at", null: false 27 | end 28 | 29 | create_table "wupee_notification_types", force: :cascade do |t| 30 | t.string "name" 31 | t.datetime "created_at", null: false 32 | t.datetime "updated_at", null: false 33 | end 34 | 35 | add_index "wupee_notification_types", ["name"], name: "index_wupee_notification_types_on_name", unique: true 36 | 37 | create_table "wupee_notifications", force: :cascade do |t| 38 | t.integer "receiver_id" 39 | t.string "receiver_type" 40 | t.integer "attached_object_id" 41 | t.string "attached_object_type" 42 | t.integer "notification_type_id" 43 | t.boolean "is_read", default: false 44 | t.boolean "is_sent", default: false 45 | t.boolean "is_wanted", default: true 46 | t.datetime "created_at", null: false 47 | t.datetime "updated_at", null: false 48 | end 49 | 50 | add_index "wupee_notifications", ["attached_object_type", "attached_object_id"], name: "idx_wupee_notifications_on_attached_object_id" 51 | add_index "wupee_notifications", ["notification_type_id"], name: "idx_wupee_notifications_on_notification_type_id" 52 | add_index "wupee_notifications", ["receiver_type", "receiver_id"], name: "idx_wupee_notifications_on_receiver_id" 53 | 54 | end 55 | -------------------------------------------------------------------------------- /spec/rails_helper.rb: -------------------------------------------------------------------------------- 1 | # This file is copied to spec/ when you run 'rails generate rspec:install' 2 | ENV['RAILS_ENV'] ||= 'test' 3 | require 'spec_helper' 4 | require File.expand_path('../dummy/config/environment', __FILE__) 5 | require 'rspec/rails' 6 | require 'factory_girl_rails' 7 | 8 | # Add additional requires below this line. Rails is not loaded until this point! 9 | 10 | # Requires supporting ruby files with custom matchers and macros, etc, in 11 | # spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are 12 | # run as spec files by default. This means that files in spec/support that end 13 | # in _spec.rb will both be required and run as specs, causing the specs to be 14 | # run twice. It is recommended that you do not name files matching this glob to 15 | # end with _spec.rb. You can configure this pattern with the --pattern 16 | # option on the command line or in ~/.rspec, .rspec or `.rspec-local`. 17 | # 18 | # The following line is provided for convenience purposes. It has the downside 19 | # of increasing the boot-up time by auto-requiring all files in the support 20 | # directory. Alternatively, in the individual `*_spec.rb` files, manually 21 | # require only the support files necessary. 22 | # 23 | Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f } 24 | 25 | # Checks for pending migrations before tests are run. 26 | # If you are not using ActiveRecord, you can remove this line. 27 | ActiveRecord::Migration.maintain_test_schema! 28 | 29 | RSpec.configure do |config| 30 | # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures 31 | config.fixture_path = "#{File.dirname(__FILE__)}/fixtures" 32 | 33 | # If you're not using ActiveRecord, or you'd prefer not to run each of your 34 | # examples within a transaction, remove the following line or assign false 35 | # instead of true. 36 | config.use_transactional_fixtures = true 37 | 38 | # RSpec Rails can automatically mix in different behaviours to your tests 39 | # based on their file location, for example enabling you to call `get` and 40 | # `post` in specs under `spec/controllers`. 41 | # 42 | # You can disable this behaviour by removing the line below, and instead 43 | # explicitly tag your specs with their type, e.g.: 44 | # 45 | # RSpec.describe UsersController, :type => :controller do 46 | # # ... 47 | # end 48 | # 49 | # The different available types are documented in the features, such as in 50 | # https://relishapp.com/rspec/rspec-rails/docs 51 | config.infer_spec_type_from_file_location! 52 | end 53 | -------------------------------------------------------------------------------- /spec/models/notifier_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | require_relative '../../lib/wupee/notifier' 3 | 4 | RSpec.describe Wupee::Notifier, type: :model do 5 | let!(:notif_type) { Wupee::NotificationType.create!(name: "notify_new_message") } 6 | let!(:user) { create :user } 7 | 8 | context "methods defined" do 9 | it { expect(subject).to respond_to(:notif_type) } 10 | it { expect(subject).to respond_to(:attached_object) } 11 | it { expect(subject).to respond_to(:receiver) } 12 | it { expect(subject).to respond_to(:receivers) } 13 | it { expect(subject).to respond_to(:deliver) } 14 | it { expect(subject).to respond_to(:subject_vars) } 15 | end 16 | 17 | it "has a method notif_type that can take Wupee::NotificationType instance or string/symbol as argument" do 18 | wupee_notifier = Wupee::Notifier.new 19 | wupee_notifier.notif_type(notif_type.name) 20 | expect(wupee_notifier.notification_type).to eq notif_type 21 | 22 | wupee_notifier.notif_type(notif_type) 23 | expect(wupee_notifier.notification_type).to eq notif_type 24 | end 25 | 26 | it "has a method execute to send notifications and mails" do 27 | user_1 = create :user 28 | user_2 = create :user 29 | user_3 = create :user 30 | user_4 = create :user 31 | 32 | wupee_notifier = Wupee::Notifier.new(receivers: [user_1, user_2, user_3, user_4], notif_type: notif_type) 33 | 34 | expect { wupee_notifier.execute }.to change { ActionMailer::Base.deliveries.size }.by(4) 35 | expect { wupee_notifier.execute }.to change { Wupee::Notification.where(is_read: false).count }.by(4) 36 | expect { wupee_notifier.execute }.to change { Wupee::Notification.count }.by(4) 37 | 38 | Wupee.email_sending_rule = false 39 | expect { wupee_notifier.execute }.not_to change { ActionMailer::Base.deliveries.size } 40 | expect { wupee_notifier.execute }.to change { Wupee::Notification.count }.by(4) 41 | 42 | Wupee.notification_sending_rule = false 43 | expect { wupee_notifier.execute }.not_to change { Wupee::Notification.wanted.count } 44 | expect { wupee_notifier.execute }.to change { Wupee::Notification.unwanted.count }.by(4) 45 | end 46 | 47 | it "raises ArgumentError if receiver or receivers is missing" do 48 | expect { Wupee::Notifier.new(notif_type: notif_type).execute }.to raise_error(ArgumentError) 49 | end 50 | 51 | it "doesn't raise ArgumentError if receiver or receivers is present" do 52 | expect { Wupee::Notifier.new(notif_type: notif_type, receiver: user).execute }.not_to raise_error 53 | expect { Wupee::Notifier.new(notif_type: notif_type, receivers: user).execute }.not_to raise_error 54 | end 55 | 56 | it "doesn't raise ArgumentError if receivers is an empty array" do 57 | expect { Wupee::Notifier.new(notif_type: notif_type, receivers: []).execute }.not_to raise_error 58 | end 59 | 60 | it "raises ArgumentError if notif_type is missing" do 61 | expect { Wupee::Notifier.new(receiver: user).execute }.to raise_error(ArgumentError) 62 | end 63 | end 64 | -------------------------------------------------------------------------------- /spec/dummy/config/environments/production.rb: -------------------------------------------------------------------------------- 1 | Rails.application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb. 3 | 4 | # Code is not reloaded between requests. 5 | config.cache_classes = true 6 | 7 | # Eager load code on boot. This eager loads most of Rails and 8 | # your application in memory, allowing both threaded web servers 9 | # and those relying on copy on write to perform better. 10 | # Rake tasks automatically ignore this option for performance. 11 | config.eager_load = true 12 | 13 | # Full error reports are disabled and caching is turned on. 14 | config.consider_all_requests_local = false 15 | config.action_controller.perform_caching = true 16 | 17 | # Enable Rack::Cache to put a simple HTTP cache in front of your application 18 | # Add `rack-cache` to your Gemfile before enabling this. 19 | # For large-scale production use, consider using a caching reverse proxy like 20 | # NGINX, varnish or squid. 21 | # config.action_dispatch.rack_cache = true 22 | 23 | # Disable serving static files from the `/public` folder by default since 24 | # Apache or NGINX already handles this. 25 | config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present? 26 | 27 | # Compress JavaScripts and CSS. 28 | config.assets.js_compressor = :uglifier 29 | # config.assets.css_compressor = :sass 30 | 31 | # Do not fallback to assets pipeline if a precompiled asset is missed. 32 | config.assets.compile = false 33 | 34 | # Asset digests allow you to set far-future HTTP expiration dates on all assets, 35 | # yet still be able to expire them through the digest params. 36 | config.assets.digest = true 37 | 38 | # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb 39 | 40 | # Specifies the header that your server uses for sending files. 41 | # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache 42 | # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX 43 | 44 | # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. 45 | # config.force_ssl = true 46 | 47 | # Use the lowest log level to ensure availability of diagnostic information 48 | # when problems arise. 49 | config.log_level = :debug 50 | 51 | # Prepend all log lines with the following tags. 52 | # config.log_tags = [ :subdomain, :uuid ] 53 | 54 | # Use a different logger for distributed setups. 55 | # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) 56 | 57 | # Use a different cache store in production. 58 | # config.cache_store = :mem_cache_store 59 | 60 | # Enable serving of images, stylesheets, and JavaScripts from an asset server. 61 | # config.action_controller.asset_host = 'http://assets.example.com' 62 | 63 | # Ignore bad email addresses and do not raise email delivery errors. 64 | # Set this to true and configure the email server for immediate delivery to raise delivery errors. 65 | # config.action_mailer.raise_delivery_errors = false 66 | 67 | # Enable locale fallbacks for I18n (makes lookups for any locale fall back to 68 | # the I18n.default_locale when a translation cannot be found). 69 | config.i18n.fallbacks = true 70 | 71 | # Send deprecation notices to registered listeners. 72 | config.active_support.deprecation = :notify 73 | 74 | # Use default logging formatter so that PID and timestamp are not suppressed. 75 | config.log_formatter = ::Logger::Formatter.new 76 | 77 | # Do not dump schema after migrations. 78 | config.active_record.dump_schema_after_migration = false 79 | end 80 | -------------------------------------------------------------------------------- /lib/wupee/notifier.rb: -------------------------------------------------------------------------------- 1 | module Wupee 2 | class Notifier 3 | attr_reader :deliver_when, :attached_object, :receiver_s, :notification_type, :subject_vars, :locals, :headers, :config_scope 4 | 5 | def initialize(opts = {}) 6 | @attached_object = opts[:attached_object] 7 | 8 | receiver_arg = opts[:receiver] || opts[:receivers] 9 | receiver(receiver_arg) if receiver_arg 10 | 11 | @subject_vars = opts[:subject_vars] || {} 12 | @locals = opts[:locals] || {} 13 | 14 | @headers = opts[:headers] || {} 15 | 16 | @config_scope = opts[:config_scope] 17 | 18 | @deliver_when = opts[:deliver] 19 | notif_type(opts[:notif_type]) if opts[:notif_type] 20 | end 21 | 22 | def headers(headers = {}) 23 | @headers = headers 24 | end 25 | 26 | def notif_type(notif_type) 27 | if notif_type.is_a?(Wupee::NotificationType) 28 | @notification_type = notif_type 29 | else 30 | @notification_type = Wupee::NotificationType.find_by!(name: notif_type) 31 | end 32 | end 33 | 34 | def attached_object(attached_object) 35 | @attached_object = attached_object 36 | end 37 | 38 | def receiver(receiver) 39 | @receiver_s = [*receiver] 40 | end 41 | 42 | def receivers(receivers) 43 | receiver(receivers) 44 | end 45 | 46 | def deliver(deliver_method) 47 | @deliver_when = deliver_method 48 | end 49 | 50 | def subject_vars(subject_vars = {}) 51 | @subject_vars = subject_vars 52 | end 53 | 54 | def locals(locals = {}) 55 | @locals = locals 56 | end 57 | 58 | def execute 59 | raise ArgumentError.new('receiver or receivers is missing') if @receiver_s.nil? 60 | raise ArgumentError.new('notif_type is missing') if @notification_type.nil? 61 | 62 | notifications = [] 63 | @receiver_s.each do |receiver| 64 | notification = Wupee::Notification.new(receiver: receiver, notification_type: @notification_type, attached_object: @attached_object) 65 | 66 | notification.is_wanted = false unless send_notification?(receiver, @notification_type) 67 | 68 | notification.save! 69 | 70 | notifications << notification 71 | 72 | subject_interpolations = interpolate_vars(@subject_vars, notification) 73 | locals_interpolations = interpolate_vars(@locals, notification) 74 | 75 | send_email(notification, subject_interpolations, locals_interpolations) if send_email?(receiver, @notification_type) 76 | end 77 | 78 | notifications 79 | end 80 | 81 | private 82 | def send_email(notification, subject_interpolations, locals_interpolations) 83 | deliver_method = "deliver_#{@deliver_when || Wupee.deliver_when}" 84 | Wupee.mailer.send_mail_for(notification, subject_interpolations, locals_interpolations, @headers).send(deliver_method) 85 | end 86 | 87 | def interpolate_vars(vars, notification) 88 | vars_interpolated = {} 89 | vars.each do |key, value| 90 | vars_interpolated[key] = if value.kind_of?(Proc) 91 | notification.instance_eval(&value) 92 | else 93 | value 94 | end 95 | end 96 | 97 | vars_interpolated 98 | end 99 | 100 | def send_notification?(receiver, notification_type) 101 | if !Wupee.notification_sending_rule.nil? 102 | if Wupee.notification_sending_rule.is_a?(Proc) 103 | Wupee.notification_sending_rule.call(receiver, notification_type) 104 | else 105 | Wupee.notification_sending_rule 106 | end 107 | else 108 | true 109 | end 110 | end 111 | 112 | def send_email?(receiver, notification_type) 113 | if !Wupee.email_sending_rule.nil? 114 | if Wupee.email_sending_rule.is_a?(Proc) 115 | Wupee.email_sending_rule.call(receiver, notification_type) 116 | else 117 | Wupee.email_sending_rule 118 | end 119 | else 120 | true 121 | end 122 | end 123 | end 124 | end 125 | -------------------------------------------------------------------------------- /spec/spec_helper.rb: -------------------------------------------------------------------------------- 1 | # This file was generated by the `rails generate rspec:install` command. Conventionally, all 2 | # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. 3 | # The generated `.rspec` file contains `--require spec_helper` which will cause 4 | # this file to always be loaded, without a need to explicitly require it in any 5 | # files. 6 | # 7 | # Given that it is always loaded, you are encouraged to keep this file as 8 | # light-weight as possible. Requiring heavyweight dependencies from this file 9 | # will add to the boot time of your test suite on EVERY test run, even for an 10 | # individual file that may not need all of that loaded. Instead, consider making 11 | # a separate helper file that requires the additional dependencies and performs 12 | # the additional setup, and require it from the spec files that actually need 13 | # it. 14 | # 15 | # The `.rspec` file also contains a few flags that are not defaults but that 16 | # users commonly want. 17 | # 18 | # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration 19 | RSpec.configure do |config| 20 | # rspec-expectations config goes here. You can use an alternate 21 | # assertion/expectation library such as wrong or the stdlib/minitest 22 | # assertions if you prefer. 23 | config.expect_with :rspec do |expectations| 24 | # This option will default to `true` in RSpec 4. It makes the `description` 25 | # and `failure_message` of custom matchers include text for helper methods 26 | # defined using `chain`, e.g.: 27 | # be_bigger_than(2).and_smaller_than(4).description 28 | # # => "be bigger than 2 and smaller than 4" 29 | # ...rather than: 30 | # # => "be bigger than 2" 31 | expectations.include_chain_clauses_in_custom_matcher_descriptions = true 32 | end 33 | 34 | # rspec-mocks config goes here. You can use an alternate test double 35 | # library (such as bogus or mocha) by changing the `mock_with` option here. 36 | config.mock_with :rspec do |mocks| 37 | # Prevents you from mocking or stubbing a method that does not exist on 38 | # a real object. This is generally recommended, and will default to 39 | # `true` in RSpec 4. 40 | mocks.verify_partial_doubles = true 41 | end 42 | 43 | # The settings below are suggested to provide a good initial experience 44 | # with RSpec, but feel free to customize to your heart's content. 45 | =begin 46 | # These two settings work together to allow you to limit a spec run 47 | # to individual examples or groups you care about by tagging them with 48 | # `:focus` metadata. When nothing is tagged with `:focus`, all examples 49 | # get run. 50 | config.filter_run :focus 51 | config.run_all_when_everything_filtered = true 52 | 53 | # Limits the available syntax to the non-monkey patched syntax that is 54 | # recommended. For more details, see: 55 | # - http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax 56 | # - http://teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ 57 | # - http://myronmars.to/n/dev-blog/2014/05/notable-changes-in-rspec-3#new__config_option_to_disable_rspeccore_monkey_patching 58 | config.disable_monkey_patching! 59 | 60 | # Many RSpec users commonly either run the entire suite or an individual 61 | # file, and it's useful to allow more verbose output when running an 62 | # individual spec file. 63 | if config.files_to_run.one? 64 | # Use the documentation formatter for detailed output, 65 | # unless a formatter has already been configured 66 | # (e.g. via a command-line flag). 67 | config.default_formatter = 'doc' 68 | end 69 | 70 | # Print the 10 slowest examples and example groups at the 71 | # end of the spec run, to help surface which specs are running 72 | # particularly slow. 73 | config.profile_examples = 10 74 | 75 | # Run specs in random order to surface order dependencies. If you find an 76 | # order dependency and want to debug it, you can fix the order by providing 77 | # the seed, which is printed after each run. 78 | # --seed 1234 79 | config.order = :random 80 | 81 | # Seed global randomization in this process using the `--seed` CLI option. 82 | # Setting this allows you to use `--seed` to deterministically reproduce 83 | # test failures related to randomization by passing the same `--seed` value 84 | # as the one that triggered the failure. 85 | Kernel.srand config.seed 86 | =end 87 | end 88 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Breaking changes 2 | 3 | After using this gem in a few projects, I realized that all projects have different needs concerning the configuration of notifications (whether or not the user should received a notification or an email). We have apps which doesn't have the need for configuration so we are having a lots of Wupee::NotificationTypeConfiguration created and fetched from db for nothing. I really feel that the app should be responsible for addressing this. 4 | Also, in some apps, I had to reopen classes to override default behaviour of the gem or skip callbacks and adding others and I was feeling that something was wrong. See [this issue](https://github.com/sleede/wupee/issues/7) for another example. 5 | Therefore, this branch removes all Wupee::NotificationTypeConfiguration but leaves a door open to customization, see [Wupee initializer](#initializer). 6 | 7 | 8 | # Wupee 9 | 10 | Wupee is a simple gem which tries to fill the gap of lacking gems to manage **notifications** in Rails app. 11 | Wupee is an opinionated solution which assumes that users needs to: 12 | 13 | * be able to receive notifications in the app 14 | * be able to receive notifications by email 15 | 16 | The main object of the solution is the `Wupee::Notification` which stores: 17 | * receiver (polymorphic): the recipient of the message 18 | * attached_object (polymorphic): the subject of the notification 19 | * notification_type_id: a reference to a `Wupee::NotificationType` object 20 | * is_read: boolean 21 | 22 | 23 | ## Install: 24 | 25 | To use it, add it to your Gemfile: 26 | ```ruby 27 | gem 'wupee' 28 | ``` 29 | 30 | and bundle: 31 | ```bash 32 | $ bundle 33 | ``` 34 | 35 | Run the generator, install migrations and migrate: 36 | 37 | ```bash 38 | $ rails g wupee:install 39 | $ rake wupee:install:migrations 40 | $ rake db:migrate 41 | ``` 42 | 43 | Running the generator will do a few things: 44 | 45 | 1. create wupee initializer: 46 | 47 | ```ruby 48 | # config/initializers/wupee.rb 49 | Wupee.mailer = NotificationsMailer # the class of the mailer you will use to send the emails 50 | Wupee.deliver_when = :now # use :later if you already configured a queuing system 51 | 52 | # uncomment and implement your logic here to avoid/permit email sending to your users 53 | # leave it commented if you always want your users received emails 54 | # Wupee.email_sending_rule = Proc.new do |receiver, notification_type| 55 | # # logic goes here, returning a boolean 56 | # end 57 | 58 | # uncomment and implement your logic here to avoid/permit email sending to your users 59 | # leave it commented if you always want your users received notifications 60 | # Wupee.notification_sending_rule = Proc.new do |receiver, notification_type| 61 | # # logic goes here, returning a boolean 62 | # end 63 | ``` 64 | 2. create a mailer `NotificationsMailer` which inheritates from `Wupee::NotificationsMailer` 65 | 66 | ```ruby 67 | # app/mailers/notifications_mailer.rb 68 | class NotificationsMailer < Wupee::NotificationsMailer 69 | default from: 'contact@sleede.com' 70 | layout false 71 | end 72 | ``` 73 | 74 | 3. adds wupee to your locale yml file (for email subjects) 75 | ```yml 76 | # config/locales/en.yml 77 | en: 78 | wupee: 79 | email_subjects: 80 | ``` 81 | 82 | ## Getting started: 83 | 84 | ### Generate a new notification type 85 | 86 | ```bash 87 | rails g wupee:notification_type user_has_been_created 88 | ``` 89 | 90 | Will execute a few things: 91 | 92 | 1. add an entry to your locale yml file : 93 | 94 | ```yml 95 | en: 96 | wupee: 97 | email_subjects: 98 | user_has_been_created: "user_has_been_created" 99 | ``` 100 | Feel free to edit the subject, you can put variables, example 101 | ```yml 102 | ... 103 | user_has_been_created: "New user created: %{user_full_name}" 104 | ``` 105 | 106 | 2. create a json template for the notification: 107 | 108 | ```ruby 109 | json.subject "" 110 | json.body "" 111 | json.url "" 112 | # none of this json attribute are mandatory! 113 | ``` 114 | In this template, you have access to the **notification** variable. 115 | You can customize it to fit your need, this is just an example. 116 | 117 | 3. create an empty html template for the notification: 118 | ```html 119 | 120 | ``` 121 | 122 | 4. You will have to create your email template as the generator doesn't create it. 123 | For example, if your mailer is named `NotificationsMailer`, your template will take place in 124 | `app/views/notifications_mailer/user_has_been_created.html.erb` 125 | 126 | 127 | ### Use the concerns 128 | 129 | #### Wupee::Receiver 130 | 131 | Including the concern `Wupee::Receiver` in your receiver class (probably the `User` class) permits a few things: 132 | * get notifications of a user: `@user.notifications` 133 | * destroy `Wupee::Notification` associated to the receiver from db if it is destroyed 134 | 135 | #### Wupee::AttachedObject 136 | 137 | Including the concern `Wupee::AttachedObject` in your attached object classe(s) permits a few things: 138 | * get notifications associated to an attached object: `@attached_object.notifications_as_attached_object` 139 | * destroy `Wupee::Notification` associated to the attached object if it is destroyed 140 | 141 | ### Use the DSL to send notifications 142 | 143 | Imagine that you want to notify all admin that a new user signed up in your app and that you have a scope `admin` in your `User` class. 144 | 145 | ```ruby 146 | Wupee.notify do |n| 147 | n.attached_object @the_new_user 148 | n.notif_type :user_has_been_created # you can also pass an instance of a Wupee::NotificationType class to this method 149 | n.subject_vars user_full_name: Proc.new { |notification| notification.attached_object.full_name } # variables to be interpolated the fill in the subject of the email (obviously optional) 150 | n.locals extra_data: "something" # extra_data will be accessible in template as @locals[:extra_data] 151 | n.receivers User.admin # you can use the method receiver instead of receivers for clarity if you pass only one instance of a receiver 152 | n.deliver :now # you can overwrite global configuration here, optional 153 | end 154 | ``` 155 | 156 | You can also use the method `notify` this way: 157 | 158 | ```ruby 159 | Wupee.notify attached_object: @the_new_user, notif_type: :user_has_been_created, subject_vars: { user_full_name: Proc.new { |notification| notification.attached_object.full_name } }, locals: { extra_data: "Yeahhhhh" }, receivers: User.admin 160 | ``` 161 | 162 | ## Wupee::Api::NotificationsController 163 | 164 | The controller have various actions all scoped for the current user: 165 | * `wupee/api/notifications#index` : fetch notifications, takes an optional get parameter `scopes` (example: scopes=read,ordered) 166 | * `wupee/api/notifications#show` : fetch a notification 167 | * `wupee/api/notifications#mark_as_read` : mark a notification as read 168 | * `wupee/api/notifications#mark_all_as_read` : mark all notifications as read 169 | 170 | To use this controller, define a controller inheriting from `Wupee::Api::NotificationsController`, set the routes in your `config/routes.rb` 171 | and define a method `current_user` which returns the user signed in. 172 | 173 | Example: 174 | ```ruby 175 | # config/routes.rb 176 | namespace :api, defaults: { format: :json } do 177 | resources :notifications, only: [:index, :show] do 178 | patch :mark_as_read, on: :member 179 | patch :mark_all_as_read, on: :collection 180 | end 181 | end 182 | 183 | # app/controllers/api/notifications_controller.rb 184 | class Api::NotificationsController < Wupee::Api::NotificationsController 185 | before_action :authenticate_user! # if you are using devise 186 | end 187 | ``` 188 | 189 | ## Why WUPEE ? 190 | 191 | **W**hat's **UP** Sl**EE**de 192 | 193 | ## License 194 | 195 | This project rocks and uses MIT-LICENSE. 196 | --------------------------------------------------------------------------------