unread 0.14.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,15 +1,18 @@
1
1
  class ReadMark < ActiveRecord::Base
2
- belongs_to :readable, polymorphic: true, inverse_of: :read_marks
2
+ # A global read mark has no readable, so both associations must be optional.
3
+ # The model is loaded before the app config is applied, so be explicit here.
4
+ belongs_to :readable, polymorphic: true, inverse_of: :read_marks, optional: true
5
+ belongs_to :reader, polymorphic: true, inverse_of: :read_marks, optional: true
3
6
 
4
- validates_presence_of :reader_id, :reader_type, :readable_type
7
+ validates :reader_id, :reader_type, :readable_type, presence: true
5
8
 
6
- scope :global, lambda { where(readable_id: nil) }
7
- scope :single, lambda { where('readable_id IS NOT NULL') }
8
- scope :older_than, lambda { |timestamp| where([ 'timestamp < ?', timestamp ]) }
9
+ scope :global, -> { where(readable_id: nil) }
10
+ scope :single, -> { where.not(readable_id: nil) }
11
+ scope :older_than, ->(timestamp) { where(timestamp: ...timestamp) }
9
12
 
10
- # Returns the classes defined by acts_as_reader
11
- class_attribute :reader_classes
13
+ # Classes defined by acts_as_reader
14
+ class_attribute :reader_classes, default: []
12
15
 
13
- # Returns the classes defined by acts_as_readable
14
- class_attribute :readable_classes
16
+ # Classes defined by acts_as_readable
17
+ class_attribute :readable_classes, default: []
15
18
  end
@@ -5,10 +5,15 @@ module Unread
5
5
  raise ArgumentError unless options.is_a?(Hash)
6
6
 
7
7
  reader = options[:for]
8
- assert_reader(reader)
8
+ Internal.assert_reader!(reader)
9
9
 
10
10
  if target == :all
11
- reset_read_marks_for_user(reader)
11
+ # Called on a relation: mark only its records, not all records of the class
12
+ if current_scope
13
+ mark_collection_as_read(current_scope, reader)
14
+ else
15
+ reset_read_marks_for_user(reader)
16
+ end
12
17
  elsif target.respond_to?(:each)
13
18
  mark_collection_as_read(target, reader)
14
19
  else
@@ -16,139 +21,103 @@ module Unread
16
21
  end
17
22
  end
18
23
 
19
- def mark_collection_as_read(collection, reader)
20
- ReadMark.transaction do
21
- global_timestamp = reader.read_mark_global(self).try(:timestamp)
22
-
23
- collection.each do |obj|
24
- raise ArgumentError unless obj.is_a?(self)
25
- timestamp = obj.send(readable_options[:on])
26
-
27
- if global_timestamp && global_timestamp >= timestamp
28
- # The object is implicitly marked as read, so there is nothing to do
29
- else
30
- mark_collection_item_as_read(obj, reader, timestamp)
31
- end
32
- end
33
- end
34
- end
35
-
36
- def mark_collection_item_as_read(obj, reader, timestamp)
37
- marking_proc = proc {
38
- rm = obj.read_marks.find_or_initialize_by(reader: reader)
39
- rm.timestamp = timestamp
40
- rm.save!
41
- }
42
-
43
- if using_postgresql?
44
- # With PostgreSQL, a transaction is unusable after a unique constraint vialoation.
45
- # To avoid this, nested transactions are required.
46
- # http://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html#module-ActiveRecord::Transactions::ClassMethods-label-Exception+handling+and+rolling+back
47
- ReadMark.transaction(requires_new: true) do
48
- begin
49
- marking_proc.call
50
- rescue ActiveRecord::RecordNotUnique
51
- # The object is explicitly marked as read, so rollback the inner transaction
52
- raise ActiveRecord::Rollback
53
- end
54
- end
55
- else
56
- begin
57
- marking_proc.call
58
- rescue ActiveRecord::RecordNotUnique
59
- # The object is explicitly marked as read, so there is nothing to do
60
- end
61
- end
62
- end
63
-
64
- # A scope with all items accessable for the given reader
65
- # It's used in cleanup_read_marks! to support a filtered cleanup
66
- # Should be overriden if a reader doesn't have access to all items
24
+ # A scope with all items accessible for the given reader.
25
+ # It's used in cleanup_read_marks! to support a filtered cleanup.
26
+ # Override it if a reader doesn't have access to all items.
67
27
  # Default: reader has access to all items and should read them all
68
28
  #
69
29
  # Example:
70
30
  # def Message.read_scope(reader)
71
31
  # reader.visible_messages
72
32
  # end
73
- def read_scope(reader)
33
+ def read_scope(_reader)
74
34
  self
75
35
  end
76
36
 
77
- def readable_parent
78
- self.ancestors.find { |ancestor| ReadMark.readable_classes.include?(ancestor) }
79
- end
80
-
81
37
  def cleanup_read_marks!
82
- assert_reader_class
38
+ Internal.assert_reader_class!
83
39
  Unread::GarbageCollector.new(self).run!
84
40
  end
85
41
 
86
- def reset_read_marks_for_user(reader)
87
- assert_reader(reader)
42
+ private
88
43
 
44
+ def mark_collection_as_read(collection, reader)
89
45
  ReadMark.transaction do
90
- reader.read_marks.where(readable_type: self.readable_parent.name).delete_all
91
- rm = reader.read_marks.new
92
- rm.readable_type = self.readable_parent.name
93
- rm.timestamp = Time.current
94
- rm.save!
46
+ global_timestamp = reader.read_mark_global(self)&.timestamp
47
+
48
+ collection.each do |obj|
49
+ raise ArgumentError unless obj.is_a?(self)
50
+
51
+ timestamp = obj.public_send(readable_options[:on])
52
+
53
+ # Skip objects which are implicitly marked as read by the global read mark
54
+ next if global_timestamp && global_timestamp >= timestamp
55
+
56
+ mark_collection_item_as_read(obj, reader, timestamp)
57
+ end
95
58
  end
59
+ end
96
60
 
97
- reader.forget_memoized_read_mark_global
61
+ def mark_collection_item_as_read(obj, reader, timestamp)
62
+ # The savepoint keeps the outer transaction usable after a unique
63
+ # constraint violation (required by PostgreSQL)
64
+ ReadMark.transaction(requires_new: true) do
65
+ read_mark = obj.read_marks.find_or_initialize_by(reader:)
66
+ read_mark.timestamp = timestamp
67
+ read_mark.save!
68
+ rescue ActiveRecord::RecordNotUnique
69
+ # The object is already explicitly marked as read
70
+ raise ActiveRecord::Rollback
71
+ end
98
72
  end
99
73
 
100
- def assert_reader(reader)
101
- assert_reader_class
74
+ def reset_read_marks_for_user(reader)
75
+ readable_type = Internal.readable_parent(self).name
102
76
 
103
- raise ArgumentError, "Class #{reader.class.name} is not registered by acts_as_reader." unless ReadMark.reader_classes.any? { |klass| reader.is_a?(klass) }
104
- raise ArgumentError, "The given reader has no id." unless reader.id
105
- end
77
+ ReadMark.transaction do
78
+ reader.read_marks.where(readable_type:).delete_all
79
+ reader.read_marks.create!(readable_type:, timestamp: Time.current)
80
+ end
106
81
 
107
- def assert_reader_class
108
- raise RuntimeError, 'There is no class using acts_as_reader.' unless ReadMark.reader_classes
82
+ reader.send(:forget_memoized_read_mark_global)
109
83
  end
110
84
  end
111
85
 
112
86
  module InstanceMethods
113
87
  def unread?(reader)
114
- if self.respond_to?(:read_mark_id) && read_mark_id_belongs_to?(reader)
88
+ if respond_to?(:read_mark_id) && read_mark_id_belongs_to?(reader)
115
89
  # For use with scope "with_read_marks_for"
116
- return false if self.read_mark_id
90
+ return false if read_mark_id
117
91
 
118
- if global_timestamp = reader.read_mark_global(self.class).try(:timestamp)
119
- self.send(readable_options[:on]) > global_timestamp
120
- else
121
- true
122
- end
92
+ global_timestamp = reader.read_mark_global(self.class)&.timestamp
93
+ global_timestamp.nil? || public_send(readable_options[:on]) > global_timestamp
123
94
  else
124
- self.class.unread_by(reader).exists?(self.id)
95
+ self.class.unread_by(reader).exists?(id)
125
96
  end
126
97
  end
127
98
 
99
+ def read?(reader)
100
+ !unread?(reader)
101
+ end
102
+
128
103
  def mark_as_read!(options)
129
104
  reader = options[:for]
130
- self.class.assert_reader(reader)
105
+ Internal.assert_reader!(reader)
131
106
 
132
107
  ReadMark.transaction do
133
108
  if unread?(reader)
134
- rm = read_mark(reader) || read_marks.build
135
- rm.reader_id = reader.id
136
- rm.reader_type = reader.class.base_class.name
137
- rm.timestamp = self.send(readable_options[:on])
138
- rm.save!
109
+ read_mark = read_marks.find_or_initialize_by(reader:)
110
+ read_mark.timestamp = public_send(readable_options[:on])
111
+ read_mark.save!
139
112
  end
140
113
  end
141
114
  end
142
115
 
143
116
  private
144
117
 
145
- def read_mark(reader)
146
- read_marks.where(reader_id: reader.id, reader_type: reader.class.base_class.name).first
147
- end
148
-
149
118
  def read_mark_id_belongs_to?(reader)
150
- self.read_mark_reader_id.to_i == reader.id &&
151
- self.read_mark_reader_type == reader.class.base_class.name
119
+ read_mark_reader_id.to_s == reader.id.to_s &&
120
+ read_mark_reader_type == reader.class.base_class.name
152
121
  end
153
122
  end
154
123
  end
@@ -1,54 +1,62 @@
1
1
  module Unread
2
2
  module Readable
3
3
  module Scopes
4
- def join_read_marks(reader)
5
- assert_reader(reader)
6
-
7
- joins "LEFT JOIN #{ReadMark.quoted_table_name}
8
- ON #{ReadMark.quoted_table_name}.readable_type = '#{readable_parent.name}'
9
- AND #{ReadMark.quoted_table_name}.readable_id = #{quoted_table_name}.#{quoted_primary_key}
10
- AND #{ReadMark.quoted_table_name}.reader_id = #{quoted(reader.id)}
11
- AND #{ReadMark.quoted_table_name}.reader_type = #{quoted(reader.class.base_class.name)}
12
- AND #{ReadMark.quoted_table_name}.timestamp >= #{quoted_table_name}.#{connection.quote_column_name(readable_options[:on])}"
13
- end
14
-
15
4
  def unread_by(reader)
16
- result = join_read_marks(reader)
5
+ result = join_read_marks(reader).where(ReadMark.table_name => { id: nil })
17
6
 
18
- if global_time_stamp = reader.read_mark_global(self).try(:timestamp)
19
- result.where("#{ReadMark.quoted_table_name}.id IS NULL
20
- AND #{quoted_table_name}.#{connection.quote_column_name(readable_options[:on])} > ?", global_time_stamp)
7
+ if (global_timestamp = reader.read_mark_global(self)&.timestamp)
8
+ result.where("#{quoted_readable_column} > ?", global_timestamp)
21
9
  else
22
- result.where("#{ReadMark.quoted_table_name}.id IS NULL")
10
+ result
23
11
  end
24
12
  end
25
13
 
26
14
  def read_by(reader)
27
15
  result = join_read_marks(reader)
16
+ read_mark_id = "#{ReadMark.quoted_table_name}.id"
28
17
 
29
- if global_time_stamp = reader.read_mark_global(self).try(:timestamp)
30
- result.where("#{ReadMark.quoted_table_name}.id IS NOT NULL
31
- OR #{quoted_table_name}.#{connection.quote_column_name(readable_options[:on])} <= ?", global_time_stamp)
18
+ if (global_timestamp = reader.read_mark_global(self)&.timestamp)
19
+ result.where("#{read_mark_id} IS NOT NULL OR #{quoted_readable_column} <= ?", global_timestamp)
32
20
  else
33
- result.where("#{ReadMark.quoted_table_name}.id IS NOT NULL")
21
+ result.where("#{read_mark_id} IS NOT NULL")
34
22
  end
35
23
  end
36
24
 
37
25
  def with_read_marks_for(reader)
38
- postgresql_string_cast = using_postgresql? ? '::varchar' : ''
26
+ join_read_marks(reader).select(sanitize_sql_array([<<~SQL.squish, reader.class.base_class.name, reader.id]))
27
+ #{quoted_table_name}.*,
28
+ #{ReadMark.quoted_table_name}.id AS read_mark_id,
29
+ ? AS read_mark_reader_type,
30
+ ? AS read_mark_reader_id
31
+ SQL
32
+ end
39
33
 
40
- join_read_marks(reader).select("#{quoted_table_name}.*,
41
- #{ReadMark.quoted_table_name}.id AS read_mark_id,
42
- #{quoted(reader.class.base_class.name)}#{postgresql_string_cast} AS read_mark_reader_type,
43
- #{quoted(reader.id)} AS read_mark_reader_id")
34
+ private
35
+
36
+ def join_read_marks(reader)
37
+ Internal.assert_reader!(reader)
38
+
39
+ read_marks = ReadMark.quoted_table_name
40
+ sql = <<~SQL.squish
41
+ LEFT JOIN #{read_marks}
42
+ ON #{read_marks}.readable_type = :readable_type
43
+ AND #{read_marks}.readable_id = #{quoted_table_name}.#{quoted_primary_key}
44
+ AND #{read_marks}.reader_id = :reader_id
45
+ AND #{read_marks}.reader_type = :reader_type
46
+ AND #{read_marks}.timestamp >= #{quoted_readable_column}
47
+ SQL
48
+
49
+ binds = {
50
+ readable_type: Internal.readable_parent(self).name,
51
+ reader_id: reader.id,
52
+ reader_type: reader.class.base_class.name,
53
+ }
54
+
55
+ joins sanitize_sql_array([sql, binds])
44
56
  end
45
57
 
46
- def quoted(value)
47
- if Gem::Version.new(ActiveRecord::VERSION::STRING) >= Gem::Version.new('7.2')
48
- quote_bound_value(connection, value)
49
- else
50
- quote_bound_value(value)
51
- end
58
+ def quoted_readable_column
59
+ "#{quoted_table_name}.#{adapter_class.quote_column_name(readable_options[:on])}"
52
60
  end
53
61
  end
54
62
  end
data/lib/unread/reader.rb CHANGED
@@ -1,55 +1,47 @@
1
1
  module Unread
2
2
  module Reader
3
- module ClassMethods
4
- def assert_readable(readable)
5
- unless readable.respond_to?(:mark_as_read!)
6
- raise ArgumentError, "Class #{readable.class} is not registered by acts_as_readable."
7
- end
8
-
9
- unless readable.id
10
- raise ArgumentError, "The given #{readable.class} has no id."
11
- end
12
- end
13
- end
14
-
15
3
  module InstanceMethods
4
+ # The read mark that marks all items of the given readable class as read
5
+ # up to its timestamp. Memoized, including nil.
16
6
  def read_mark_global(klass)
17
7
  @read_mark_global ||= {}
18
- readable_klass = klass.readable_parent
8
+ readable_klass = Internal.readable_parent(klass)
19
9
 
20
- # Memoize with NIL handling
21
- if @read_mark_global.has_key?(readable_klass)
22
- @read_mark_global[readable_klass]
23
- else
10
+ @read_mark_global.fetch(readable_klass) do
24
11
  @read_mark_global[readable_klass] = read_marks.where(readable_type: readable_klass.name).global.first
25
12
  end
26
13
  end
27
14
 
28
- def forget_memoized_read_mark_global
29
- @read_mark_global = nil
30
- end
31
-
32
15
  def have_read?(readable)
33
- if self.respond_to?(:read_mark_id) && read_mark_id_belongs_to?(readable)
16
+ if respond_to?(:read_mark_id) && read_mark_id_belongs_to?(readable)
34
17
  # For use with scope "with_read_marks_for"
35
- !self.read_mark_id.nil?
18
+ !read_mark_id.nil?
36
19
  else
37
- !self.class.have_not_read(readable).exists?(self.id)
20
+ !self.class.have_not_read(readable).exists?(id)
38
21
  end
39
22
  end
40
23
 
24
+ def reload(...)
25
+ forget_memoized_read_mark_global
26
+ super
27
+ end
28
+
41
29
  private
42
-
30
+
31
+ def forget_memoized_read_mark_global
32
+ @read_mark_global = nil
33
+ end
34
+
43
35
  def read_mark_id_belongs_to?(readable)
44
- self.read_mark_readable_type == readable.class.name &&
45
- (self.read_mark_readable_id.nil? || self.read_mark_readable_id.to_i == readable.id)
36
+ read_mark_readable_type == readable.class.name &&
37
+ (read_mark_readable_id.nil? || read_mark_readable_id.to_s == readable.id.to_s)
46
38
  end
47
39
 
48
- # We assume that a new reader should not be tackled by tons of old messages created BEFORE he signed up.
40
+ # We assume that a new reader should not be tackled by tons of old messages created BEFORE signing up.
49
41
  # Instead, the new reader should start with zero unread messages.
50
42
  # If you don't want this, you can override this method in your reader class
51
43
  def setup_new_reader
52
- (ReadMark.readable_classes || []).each do |klass|
44
+ ReadMark.readable_classes.each do |klass|
53
45
  klass.mark_as_read! :all, for: self
54
46
  end
55
47
  end
@@ -1,46 +1,52 @@
1
1
  module Unread
2
2
  module Reader
3
3
  module Scopes
4
- # This class method may be overriden to restrict readers to a subset of records
5
- # It must return self or a ActiveRecord::Relation
4
+ # This class method may be overridden to restrict readers to a subset of records.
5
+ # It must return self or an ActiveRecord::Relation
6
6
  def reader_scope
7
7
  self
8
8
  end
9
9
 
10
- def join_read_marks(readable)
11
- assert_readable(readable)
12
-
13
- joins "LEFT JOIN #{ReadMark.quoted_table_name}
14
- ON #{ReadMark.quoted_table_name}.readable_type = '#{readable.class.readable_parent.name}'
15
- AND (#{ReadMark.quoted_table_name}.readable_id = #{quoted(readable.id)} OR #{ReadMark.quoted_table_name}.readable_id IS NULL)
16
- AND #{ReadMark.quoted_table_name}.reader_id = #{quoted_table_name}.#{quoted_primary_key}
17
- AND #{ReadMark.quoted_table_name}.reader_type = '#{connection.quote_string base_class.name}'
18
- AND #{ReadMark.quoted_table_name}.timestamp >= '#{connection.quoted_date readable.send(readable.class.readable_options[:on])}'"
19
- end
20
-
21
10
  def have_not_read(readable)
22
- join_read_marks(readable).where("#{ReadMark.quoted_table_name}.id IS NULL")
11
+ join_read_marks(readable).where(ReadMark.table_name => { id: nil })
23
12
  end
24
13
 
25
14
  def have_read(readable)
26
- join_read_marks(readable).where("#{ReadMark.quoted_table_name}.id IS NOT NULL")
15
+ join_read_marks(readable).where.not(ReadMark.table_name => { id: nil })
27
16
  end
28
17
 
29
18
  def with_read_marks_for(readable)
30
- postgresql_string_cast = using_postgresql? ? '::varchar' : ''
31
-
32
- join_read_marks(readable).select("#{quoted_table_name}.*,
33
- #{ReadMark.quoted_table_name}.id AS read_mark_id,
34
- #{quoted(readable.class.name)}#{postgresql_string_cast} AS read_mark_readable_type,
35
- #{quoted(readable.id)} AS read_mark_readable_id")
19
+ join_read_marks(readable).select(sanitize_sql_array([<<~SQL.squish, readable.class.name, readable.id]))
20
+ #{quoted_table_name}.*,
21
+ #{ReadMark.quoted_table_name}.id AS read_mark_id,
22
+ ? AS read_mark_readable_type,
23
+ ? AS read_mark_readable_id
24
+ SQL
36
25
  end
37
26
 
38
- def quoted(value)
39
- if Gem::Version.new(ActiveRecord::VERSION::STRING) >= Gem::Version.new('7.2')
40
- quote_bound_value(connection, value)
41
- else
42
- quote_bound_value(value)
43
- end
27
+ private
28
+
29
+ def join_read_marks(readable)
30
+ Internal.assert_readable!(readable)
31
+
32
+ read_marks = ReadMark.quoted_table_name
33
+ sql = <<~SQL.squish
34
+ LEFT JOIN #{read_marks}
35
+ ON #{read_marks}.readable_type = :readable_type
36
+ AND (#{read_marks}.readable_id = :readable_id OR #{read_marks}.readable_id IS NULL)
37
+ AND #{read_marks}.reader_id = #{quoted_table_name}.#{quoted_primary_key}
38
+ AND #{read_marks}.reader_type = :reader_type
39
+ AND #{read_marks}.timestamp >= :timestamp
40
+ SQL
41
+
42
+ binds = {
43
+ readable_type: Internal.readable_parent(readable.class).name,
44
+ readable_id: readable.id,
45
+ reader_type: base_class.name,
46
+ timestamp: readable.public_send(readable.class.readable_options[:on]),
47
+ }
48
+
49
+ joins sanitize_sql_array([sql, binds])
44
50
  end
45
51
  end
46
52
  end
@@ -1,3 +1,3 @@
1
1
  module Unread
2
- VERSION = '0.14.0'
2
+ VERSION = '1.0.0'.freeze
3
3
  end
data/lib/unread.rb CHANGED
@@ -1,5 +1,6 @@
1
1
  require 'active_record'
2
2
 
3
+ require 'unread/internal'
3
4
  require 'unread/base'
4
5
  require 'unread/readable'
5
6
  require 'unread/reader'
@@ -11,5 +12,5 @@ require 'unread/version'
11
12
  ActiveSupport.on_load(:active_record) do
12
13
  require 'unread/read_mark'
13
14
 
14
- include Unread
15
+ extend Unread::Base
15
16
  end