File: has_notifications.rb

package info (click to toggle)
ruby-noticed 3.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 324 kB
  • sloc: ruby: 1,186; makefile: 4
file content (49 lines) | stat: -rw-r--r-- 1,741 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
module Noticed
  module HasNotifications
    # Defines a method for the association and a before_destroy callback to remove notifications
    # where this record is a param
    #
    #    class User < ApplicationRecord
    #      has_noticed_notifications
    #      has_noticed_notifications param_name: :owner, destroy: false, model: "Notification"
    #    end
    #
    #    @user.notifications_as_user
    #    @user.notifications_as_owner

    extend ActiveSupport::Concern

    class_methods do
      def has_noticed_notifications(param_name: model_name.singular, **options)
        define_method :"notifications_as_#{param_name}" do
          model = options.fetch(:model_name, "Noticed::Event").constantize
          case current_adapter
          when "postgresql", "postgis"
            model.where("params @> ?", Noticed::Coder.dump(param_name.to_sym => self).to_json)
          when "mysql2", "trilogy"
            model.where("JSON_CONTAINS(params, ?)", Noticed::Coder.dump(param_name.to_sym => self).to_json)
          when "sqlite3"
            model.where("json_extract(params, ?) = ?", "$.#{param_name}", Noticed::Coder.dump(self).to_json)
          else
            # This will perform an exact match which isn't ideal
            model.where(params: {param_name.to_sym => self})
          end
        end

        if options.fetch(:destroy, true)
          before_destroy do
            send(:"notifications_as_#{param_name}").destroy_all
          end
        end
      end
    end

    def current_adapter
      if ActiveRecord::Base.respond_to?(:connection_db_config)
        ActiveRecord::Base.connection_db_config.adapter
      else
        ActiveRecord::Base.connection_config[:adapter]
      end
    end
  end
end