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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 67315a612c07e3b1b75c27ab34d2d29b9d7c6ae49c43b7f8fa9109ea9bf1360a
4
- data.tar.gz: 2e744db1b74319ead0e3166a127b7bb21791fb41e0ffeed0211b8a0427778fed
3
+ metadata.gz: 781c2331dbe84fa2e8713d49f178147c323e50fda48f57b0bd3c3af93c8e2078
4
+ data.tar.gz: 8c95af5aedf5dcb757d675fb28589cfaab963e4dda3677a59f30ae5c1c63ee50
5
5
  SHA512:
6
- metadata.gz: f1c031e9c0dbfab4fc028e4ad57c27aebf51f637338cd4df97b190527f98108af91bbe3fd1a525112f1c5c384da127ae197f7ddd30470933329a20bd8656135e
7
- data.tar.gz: b277d655b81d67083832e011b90301effed633ac93559cc87c589f7e44ce719414db7fb1d72d16426fe71e27ba13ab22bff0395fb83a6268c10ec280bbf57ee5
6
+ metadata.gz: 94b123407cc1525fb4c4da12aa7edc3a2f3dc8e05bcd4ed040e522ddb801e09718f48f29aa9e4df0ea428f9fc4e0c438123752273348048a858f41aa81811769
7
+ data.tar.gz: 2a7e5140a9e414b927bc94668a7d735447ea71d8a66258ca902b6eb05c06665772eede775125005ba2d8a1898e35357b026e75da44afa734a7c6d280b67ea8f4
data/MIT-LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  The MIT License (MIT)
2
2
 
3
- Copyright (c) 2010-2023 Georg Ledermann
3
+ Copyright (c) 2010-2026 Georg Ledermann
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining
6
6
  a copy of this software and associated documentation files (the
data/README.md CHANGED
@@ -1,28 +1,25 @@
1
- Unread
2
- ======
1
+ # Unread
3
2
 
4
- Ruby gem to manage read/unread status of ActiveRecord objects - and it's fast.
3
+ Ruby gem to manage the read/unread status of ActiveRecord objects.
5
4
 
6
- [![Build Status](https://github.com/ledermann/unread/workflows/Test/badge.svg?branch=master)](https://github.com/ledermann/unread/actions)
7
- [![Maintainability](https://api.codeclimate.com/v1/badges/930c8df0f99b20324444/maintainability)](https://codeclimate.com/github/ledermann/unread/maintainability)
8
- [![Coverage Status](https://coveralls.io/repos/ledermann/unread/badge.svg?branch=master)](https://coveralls.io/r/ledermann/unread?branch=master)
5
+ [![Build Status](https://github.com/ledermann/unread/actions/workflows/main.yml/badge.svg?branch=master)](https://github.com/ledermann/unread/actions)
6
+ [![Gem Version](https://badge.fury.io/rb/unread.svg)](https://badge.fury.io/rb/unread)
9
7
 
10
8
  ## Features
11
9
 
12
- * Manages unread records for anything you want readers (e.g. users) to read (like messages, documents, comments etc.)
13
- * Supports _mark as read_ to mark a **single** record as read
14
- * Supports _mark all as read_ to mark **all** records as read in a single step
15
- * Gives you a scope to get the unread records for a given reader
10
+ * Manages unread records for anything that readers (for example users) read, like messages, documents or comments
11
+ * Marks a single record as read
12
+ * Marks all records as read in one step
13
+ * Gives you a scope for the unread records of a reader
16
14
  * Needs only one additional database table
17
- * Most important: Great performance
18
15
 
19
16
 
20
17
  ## Requirements
21
18
 
22
- * Ruby 3.1 or newer
23
- * Rails 6.1 or newer (including Rails 7.2)
24
- * MySQL, PostgreSQL or SQLite
25
- * Needs a timestamp field in your models (like created_at or updated_at) with a database index on it
19
+ * Ruby 3.3 or newer
20
+ * Rails 8.1 or newer
21
+ * MySQL (with the `mysql2` or `trilogy` adapter), PostgreSQL or SQLite
22
+ * A timestamp column in your readable models (like `created_at` or `updated_at`) with a database index
26
23
 
27
24
 
28
25
  ## Changelog
@@ -32,35 +29,31 @@ https://github.com/ledermann/unread/releases
32
29
 
33
30
  ## Installation
34
31
 
35
- Step 1: Add this to your Gemfile:
32
+ 1. Add the gem to your Gemfile and install it:
36
33
 
37
- ```ruby
38
- gem 'unread'
39
- ```
34
+ ```shell
35
+ bundle add unread
36
+ ```
40
37
 
41
- and run
38
+ 2. Generate and run the migration:
42
39
 
43
- ```shell
44
- bundle
45
- ```
40
+ ```shell
41
+ bin/rails generate unread:migration
42
+ bin/rails db:migrate
43
+ ```
46
44
 
45
+ If your models use UUID primary keys, add `--primary-key-type=uuid` to the generator command.
47
46
 
48
- Step 2: Generate and run the migration:
49
-
50
- ```shell
51
- rails g unread:migration
52
- rake db:migrate
53
- ```
54
47
 
55
48
  ## Upgrade from previous releases
56
49
 
57
- If you upgrade from an older release of this gem, you should read the [upgrade notes](UPGRADE.md).
50
+ If you upgrade from an older release of this gem, read the [upgrade notes](UPGRADE.md) first.
58
51
 
59
52
 
60
53
  ## Usage
61
54
 
62
55
  ```ruby
63
- class User < ActiveRecord::Base
56
+ class User < ApplicationRecord
64
57
  acts_as_reader
65
58
 
66
59
  # Optional: Allow a subset of users as readers only
@@ -69,62 +62,58 @@ class User < ActiveRecord::Base
69
62
  end
70
63
  end
71
64
 
72
- class Message < ActiveRecord::Base
65
+ class Message < ApplicationRecord
73
66
  acts_as_readable on: :created_at
74
67
 
75
68
  # The `on:` option sets the relevant attribute for comparing timestamps.
76
69
  #
77
- # The default is :updated_at, so updating a record, which was read by a
78
- # reader makes it unread again.
70
+ # The default is :updated_at. If you update a record that a reader read,
71
+ # the record is unread again.
79
72
  #
80
- # Using :created_at, only new records will show up as unread. Updating a
81
- # record which was read by a reader, will NOT mark it as unread.
73
+ # With :created_at, only new records are unread. If you update a record
74
+ # that a reader read, the record stays read.
82
75
  #
83
- # Any other existing timestamp field can be used as `on:` option.
76
+ # You can use any other timestamp column as `on:` option.
77
+
78
+ # Optional: If a user can see only some messages, return them here.
79
+ # The cleanup with `cleanup_read_marks!` uses this scope.
80
+ def self.read_scope(user)
81
+ user.visible_messages
82
+ end
84
83
  end
85
84
 
85
+ # A new user starts with all existing messages marked as read (see
86
+ # "New readers" below). Thus, this example creates the users first.
87
+ user1 = User.create!
88
+ user2 = User.create!
89
+
86
90
  message1 = Message.create!
87
91
  message2 = Message.create!
88
92
 
89
93
  ## Get unread messages for a given user
90
- Message.unread_by(current_user)
94
+ Message.unread_by(user1)
91
95
  # => [ message1, message2 ]
92
96
 
93
- message1.mark_as_read! for: current_user
94
- Message.unread_by(current_user)
97
+ message1.mark_as_read! for: user1
98
+ Message.unread_by(user1)
95
99
  # => [ message2 ]
96
100
 
97
- ## Get read messages for a given user
98
- Message.read_by(current_user)
99
- # => [ ]
101
+ message1.read?(user1)
102
+ # => true
100
103
 
101
- message1.mark_as_read! for: current_user
102
- Message.read_by(current_user)
104
+ ## Get read messages for a given user
105
+ Message.read_by(user1)
103
106
  # => [ message1 ]
104
107
 
105
108
  ## Get all messages including the read status for a given user
106
- messages = Message.with_read_marks_for(current_user)
109
+ messages = Message.with_read_marks_for(user1)
107
110
  # => [ message1, message2 ]
108
- messages[0].unread?(current_user)
111
+ messages[0].unread?(user1)
109
112
  # => false
110
- messages[1].unread?(current_user)
113
+ messages[1].unread?(user1)
111
114
  # => true
112
115
 
113
- Message.mark_as_read! :all, for: current_user
114
- Message.unread_by(current_user)
115
- # => [ ]
116
-
117
- Message.read_by(current_user)
118
- # => [ message1, message2 ]
119
-
120
116
  ## Get users that have not read a given message
121
- user1 = User.create!
122
- user2 = User.create!
123
-
124
- User.have_not_read(message1)
125
- # => [ user1, user2 ]
126
-
127
- message1.mark_as_read! for: user1
128
117
  User.have_not_read(message1)
129
118
  # => [ user2 ]
130
119
 
@@ -132,34 +121,45 @@ User.have_not_read(message1)
132
121
  User.have_read(message1)
133
122
  # => [ user1 ]
134
123
 
135
- message1.mark_as_read! for: user2
136
- User.have_read(message1)
137
- # => [ user1, user2 ]
138
-
139
- Message.mark_as_read! :all, for: user1
140
- User.have_not_read(message1)
141
- # => [ ]
142
- User.have_not_read(message2)
143
- # => [ user2 ]
144
-
145
- User.have_read(message1)
146
- # => [ user1, user2 ]
147
- User.have_read(message2)
148
- # => [ user1 ]
149
-
150
124
  ## Get all users including their read status for a given message
151
125
  users = User.with_read_marks_for(message1)
152
126
  # => [ user1, user2 ]
153
127
  users[0].have_read?(message1)
154
128
  # => true
155
- users[1].have_read?(message2)
129
+ users[1].have_read?(message1)
156
130
  # => false
157
131
 
158
- # Optional: Cleaning up unneeded markers
159
- # Do this in a cron job once a day
132
+ ## Mark some messages as read: an array or a relation
133
+ Message.mark_as_read! [ message2 ], for: user1
134
+ Message.where(id: message2.id).mark_as_read! :all, for: user2
135
+
136
+ ## Mark all messages as read
137
+ Message.mark_as_read! :all, for: user2
138
+ Message.unread_by(user2)
139
+ # => [ ]
140
+
141
+ # Optional: Remove read marks that are no longer necessary
142
+ # Run this once a day, for example in a recurring job
160
143
  Message.cleanup_read_marks!
161
144
  ```
162
145
 
146
+ ### New readers
147
+
148
+ A new reader starts with all existing records marked as read. For this, the gem calls the method `setup_new_reader` after it creates the reader. If you want new readers to see all existing records as unread, override the method:
149
+
150
+ ```ruby
151
+ class User < ApplicationRecord
152
+ acts_as_reader
153
+
154
+ private
155
+
156
+ # All existing messages are unread for a new user
157
+ def setup_new_reader; end
158
+ end
159
+ ```
160
+
161
+ The gem knows a readable class only after Rails loads the class. Without eager loading, which is the default in development, `setup_new_reader` marks only the readable classes that Rails already loaded.
162
+
163
163
  ## Getting read/unread stats through a relationship
164
164
 
165
165
  ```ruby
@@ -183,23 +183,23 @@ end
183
183
  # => {20=>{:unread=>1, :total=>10}, 82=>{:unread=>0, :total=>4}
184
184
  ```
185
185
 
186
- Using `with_read_marks_for` here is the key. It uses just one query and makes sure that the following `unread?` invocations use the result of the first query.
186
+ The `with_read_marks_for` scope loads the read status in the same query. The `unread?` calls that follow use this result and do not send more queries.
187
187
 
188
188
  ## How does it work?
189
189
 
190
- The main idea of this gem is to manage a list of read items for every reader **after** a certain timestamp.
190
+ For each reader, the gem keeps a timestamp and a list of read items. All items older than the timestamp are read. Of the newer items, only the items in the list are read.
191
191
 
192
- The gem defines a scope doing a LEFT JOIN to this list, so your app can get the unread items in a performant manner. Of course, other scopes can be combined.
192
+ The scope `unread_by` does a LEFT JOIN to this list. You can combine it with other scopes.
193
193
 
194
- It will be ensured that the list of read items will not grow up too much:
194
+ The list does not grow without limit:
195
195
 
196
- * If a user uses "mark all as read", his list gets deleted and the timestamp is set to the current time.
197
- * If a user never uses "mark all as read", the list will grow and grow with each item he reads. But there is help: Your app can use a cleanup method which removes unnecessary list items.
196
+ * If a reader marks all items as read, the gem deletes the list and sets the timestamp to the current time.
197
+ * If a reader never marks all items as read, the list gets longer with each item that the reader reads. To remove the items that are no longer necessary, run `cleanup_read_marks!` from time to time.
198
198
 
199
- Overall, this gem can be used for large data. Please have a look at the generated SQL queries, here is an example:
199
+ Here is an example of the SQL query:
200
200
 
201
201
  ```ruby
202
- # Assuming we have a user who has marked all messages as read on 2010-10-20 08:50
202
+ # The user marked all messages as read on 2010-10-20 08:50
203
203
  current_user = User.find(42)
204
204
 
205
205
  # Get the unread messages for this user
@@ -211,7 +211,7 @@ Generated query:
211
211
  ```sql
212
212
  SELECT messages.*
213
213
  FROM messages
214
- LEFT JOIN read_marks ON read_marks.readable_type = "Message"
214
+ LEFT JOIN read_marks ON read_marks.readable_type = 'Message'
215
215
  AND read_marks.readable_id = messages.id
216
216
  AND read_marks.reader_id = 42
217
217
  AND read_marks.reader_type = 'User'
@@ -220,7 +220,31 @@ WHERE read_marks.id IS NULL
220
220
  AND messages.created_at > '2010-10-20 08:50:00'
221
221
  ```
222
222
 
223
- Hint: You should add a database index on `messages.created_at`.
223
+ ## Performance
224
+
225
+ The query for unread records reads only the records that are newer than the timestamp of the reader. If the timestamp column has an index, the size of the tables has little effect. Without this index, the database reads all records.
226
+
227
+ Thus, the time depends on the number of records after the timestamp of the reader. This number gets smaller when the reader marks all records as read. `cleanup_read_marks!` also moves the timestamp forward, up to the oldest unread record. If a reader keeps one old record unread, the number stays large.
228
+
229
+ Some operations take more time:
230
+
231
+ * `read_by` reads all records of the table.
232
+ * `mark_as_read!` with a collection sends two queries for each record.
233
+ * `cleanup_read_marks!` sends queries for each reader. Run it in a background job.
234
+
235
+
236
+ ## Development
237
+
238
+ Run the specs and RuboCop. The spec run fails if the line coverage or the branch coverage goes below 100%.
239
+
240
+ ```shell
241
+ bundle install
242
+ bundle exec rake
243
+ ```
244
+
245
+ The specs use SQLite by default. To use another database, set `DB` to `mysql`, `trilogy` or `postgres`. The connection data is in `spec/database.yml`. To use other ports, set `MYSQL_PORT` or `POSTGRES_PORT`.
246
+
247
+ To test with another Rails version, set `RAILS_VERSION`, for example `RAILS_VERSION=edge`.
224
248
 
225
249
 
226
- Copyright (c) 2010-2023 [Georg Ledermann](https://ledermann.dev) and [contributors](https://github.com/ledermann/unread/graphs/contributors), released under the MIT license
250
+ Copyright (c) 2010-2026 [Georg Ledermann](https://ledermann.dev) and [contributors](https://github.com/ledermann/unread/graphs/contributors), released under the MIT license
data/UPGRADE.md CHANGED
@@ -1,49 +1,50 @@
1
1
  # Upgrade notes
2
2
 
3
- ## Breaking changes with v0.7.0
3
+ ## Upgrade to v1.0.0
4
4
 
5
- There are two important changes needing your attention. Please read the following hints carefully!
5
+ ### Ruby and Rails versions
6
6
 
7
+ The gem supports only Ruby and Rails versions that still get security fixes:
7
8
 
8
- ### Polymorphic readers
9
+ * Ruby 3.3 or newer
10
+ * Rails 8.1 or newer
9
11
 
10
- The gem accepts any type of classes as reader and it's not limited to `User` class anymore. So you can do stuff like:
12
+ If your app uses an older version, stay on v0.14.0.
11
13
 
12
- ```ruby
13
- Customer.have_not_read(message1)
14
- message1.mark_as_read! for: Customer.find(1)
15
- ```
14
+ ### Public API
16
15
 
17
- If you are upgrading from v0.6.3 or older, you need to do the following after upgrading:
16
+ The gem adds fewer methods to your models. These methods are the public API:
18
17
 
19
- ```shell
20
- rails g unread:polymorphic_reader_migration
21
- rake db:migrate
22
- ```
18
+ * Reader class: `acts_as_reader`, `have_read`, `have_not_read`, `with_read_marks_for`, `reader_scope`
19
+ * Reader instance: `have_read?`, `read_mark_global`
20
+ * Readable class: `acts_as_readable`, `unread_by`, `read_by`, `with_read_marks_for`, `mark_as_read!`, `cleanup_read_marks!`, `read_scope`, `readable_options`
21
+ * Readable instance: `unread?`, `read?`, `mark_as_read!`
23
22
 
24
- This will alter the `read_marks` table to replace `user` association to a polymorphic association named `reader`. Therefore, `user_id` is going to be renamed to `reader_id` and `reader_type` is going to be added.
23
+ The other methods are now private or moved to `Unread::Internal`:
25
24
 
26
- This change should not break your code unless you've worked with `ReadMark` model directly.
25
+ * `join_read_marks`
26
+ * `mark_collection_as_read` and `mark_collection_item_as_read`
27
+ * `reset_read_marks_for_user`: Use `mark_as_read!(:all, for: reader)`.
28
+ * `readable_parent`
29
+ * `assert_reader`, `assert_reader_class` and `assert_readable`
30
+ * `forget_memoized_read_mark_global`: Use `reload` on the reader. It also clears the memoized global read mark.
31
+ * `using_postgresql?`
27
32
 
33
+ If your app calls one of these methods, change it before you upgrade.
28
34
 
29
- ### Defining reader_scope
35
+ ### Migration generator
30
36
 
31
- The class method `acts_as_reader` doesn't take the option `:scope` anymore. If you have used it, please change this ...
37
+ The generator `unread:migration` changed for new installations:
32
38
 
33
- ```ruby
34
- class User < ActiveRecord::Base
35
- acts_as_reader scope: -> { where(is_admin: true) }
36
- end
37
- ```
39
+ * The migration uses the current Rails migration version and a `change` method.
40
+ * On MySQL, the table uses the default character set of the database. The old migration set `latin1`.
41
+ * The column `reader_id` is `NOT NULL`.
42
+ * The new option `--primary-key-type` sets the type of the id columns, for example `uuid`.
38
43
 
39
- ... to this
44
+ You do not have to change existing `read_marks` tables, but we recommend one change. Older releases created the column `timestamp` without fractional seconds. Then a record that a reader marks as read in the same second as its creation can stay unread. If `db/schema.rb` shows `precision: nil` for this column, add a migration:
40
45
 
41
46
  ```ruby
42
- class User < ActiveRecord::Base
43
- acts_as_reader
44
-
45
- def self.reader_scope
46
- where(is_admin: true)
47
- end
48
- end
47
+ change_column :read_marks, :timestamp, :datetime, precision: 6
49
48
  ```
49
+
50
+ The generator `unread:polymorphic_reader_migration` was removed. If you upgrade from v0.6.3 or older, upgrade to v0.14.0 first. Then follow the [upgrade notes of v0.14.0](https://github.com/ledermann/unread/blob/v0.14.0/UPGRADE.md).
@@ -1,34 +1,18 @@
1
1
  require 'rails/generators'
2
- require 'rails/generators/migration'
2
+ require 'rails/generators/active_record'
3
3
 
4
4
  module Unread
5
5
  class MigrationGenerator < Rails::Generators::Base
6
- include Rails::Generators::Migration
6
+ include ActiveRecord::Generators::Migration
7
7
 
8
- desc "Generates migration for read_markers"
9
- source_root File.expand_path('../templates', __FILE__)
8
+ desc 'Generates migration for read_marks'
9
+ source_root File.expand_path('templates', __dir__)
10
10
 
11
- def create_migration_file
12
- migration_template 'migration.rb', 'db/migrate/unread_migration.rb'
13
- end
11
+ class_option :primary_key_type, type: :string,
12
+ desc: 'The type of the reader and readable id columns, for example uuid'
14
13
 
15
- def self.next_migration_number(dirname)
16
- if self.timestamped_migrations?
17
- Time.now.utc.strftime("%Y%m%d%H%M%S")
18
- else
19
- "%.3d" % (current_migration_number(dirname) + 1)
20
- end
21
- end
22
-
23
- def self.timestamped_migrations?
24
- (
25
- ActiveRecord::Base.respond_to?(:timestamped_migrations) &&
26
- ActiveRecord::Base.timestamped_migrations
27
- ) ||
28
- (
29
- ActiveRecord.respond_to?(:timestamped_migrations) &&
30
- ActiveRecord.timestamped_migrations
31
- )
14
+ def create_migration_file
15
+ migration_template 'migration.rb', File.join(db_migrate_path, 'unread_migration.rb')
32
16
  end
33
17
  end
34
18
  end
@@ -0,0 +1,13 @@
1
+ class UnreadMigration < ActiveRecord::Migration[<%= ActiveRecord::Migration.current_version %>]
2
+ def change
3
+ create_table :read_marks do |t|
4
+ # readable_id is NULL for the global read mark of a reader
5
+ t.references :readable, polymorphic: { null: false }<%= foreign_key_type %>
6
+ t.references :reader, polymorphic: true, null: false<%= foreign_key_type %>
7
+ t.datetime :timestamp, null: false
8
+ end
9
+
10
+ add_index :read_marks, %i[reader_id reader_type readable_type readable_id],
11
+ name: 'read_marks_reader_readable_index', unique: true
12
+ end
13
+ end
data/lib/unread/base.rb CHANGED
@@ -1,48 +1,30 @@
1
1
  module Unread
2
- def self.included(base)
3
- base.extend Base
4
- end
5
-
6
2
  module Base
7
3
  def acts_as_reader
8
- ReadMark.reader_classes ||= []
9
-
10
- unless ReadMark.reader_classes.include?(self)
11
- ReadMark.belongs_to :reader, polymorphic: true, inverse_of: :read_marks, optional: true
4
+ return if ReadMark.reader_classes.include?(self)
12
5
 
13
- has_many :read_marks, dependent: :delete_all, as: :reader, inverse_of: :reader
6
+ has_many :read_marks, dependent: :delete_all, as: :reader, inverse_of: :reader
14
7
 
15
- after_create :setup_new_reader
8
+ after_create :setup_new_reader
16
9
 
17
- ReadMark.reader_classes << self
10
+ ReadMark.reader_classes << self
18
11
 
19
- include Reader::InstanceMethods
20
- extend Reader::ClassMethods
21
- extend Reader::Scopes
22
- end
12
+ include Reader::InstanceMethods
13
+ extend Reader::Scopes
23
14
  end
24
15
 
25
- def acts_as_readable(options={})
26
- ReadMark.readable_classes ||= []
16
+ def acts_as_readable(options = {})
17
+ return if ReadMark.readable_classes.include?(self)
27
18
 
28
- unless ReadMark.readable_classes.include?(self)
29
- class_attribute :readable_options
19
+ class_attribute :readable_options, default: options.reverse_merge(on: :updated_at)
30
20
 
31
- options.reverse_merge!(on: :updated_at)
32
- self.readable_options = options
21
+ has_many :read_marks, as: :readable, dependent: :delete_all, inverse_of: :readable
33
22
 
34
- has_many :read_marks, as: :readable, dependent: :delete_all, inverse_of: :readable
35
-
36
- ReadMark.readable_classes << self
37
-
38
- include Readable::InstanceMethods
39
- extend Readable::ClassMethods
40
- extend Readable::Scopes
41
- end
42
- end
23
+ ReadMark.readable_classes << self
43
24
 
44
- def using_postgresql?
45
- connection.adapter_name.match(/postgres/i)
25
+ include Readable::InstanceMethods
26
+ extend Readable::ClassMethods
27
+ extend Readable::Scopes
46
28
  end
47
29
  end
48
30
  end
@@ -1,54 +1,52 @@
1
1
  module Unread
2
2
  class GarbageCollector
3
3
  def initialize(readable_class)
4
- @readable_class = readable_class.readable_parent
4
+ @readable_class = Internal.readable_parent(readable_class)
5
5
  end
6
6
  attr_reader :readable_class
7
7
 
8
8
  def run!
9
9
  ReadMark.reader_classes.each do |reader_class|
10
10
  readers_to_cleanup(reader_class).find_each do |reader|
11
- if oldest_timestamp = readable_class.read_scope(reader).
12
- unread_by(reader).
13
- minimum(readable_class.readable_options[:on])
11
+ oldest_timestamp = readable_class
12
+ .read_scope(reader)
13
+ .unread_by(reader)
14
+ .minimum(readable_class.readable_options[:on])
15
+
16
+ if oldest_timestamp
14
17
  # There are unread items, so update the global read_mark for this reader to the oldest
15
18
  # unread item and delete older read_marks
16
19
  update_read_marks_for_user(reader, oldest_timestamp)
17
20
  else
18
- # There is no unread item, so deletes all markers and move global timestamp
19
- readable_class.reset_read_marks_for_user(reader)
21
+ # There is no unread item, so delete all markers and move global timestamp
22
+ readable_class.mark_as_read!(:all, for: reader)
20
23
  end
21
24
  end
22
25
  end
23
26
  end
24
27
 
25
- private
26
- # Not for every reader a cleanup is needed.
27
- # Look for those readers with at least one single read mark
28
+ private
29
+
30
+ # Not every reader needs a cleanup.
31
+ # Look for those readers with more than one read mark
28
32
  def readers_to_cleanup(reader_class)
29
- reader_class.
30
- reader_scope.
31
- joins(:read_marks).
32
- where(ReadMark.table_name => { readable_type: readable_class.name }).
33
- group("#{ReadMark.quoted_table_name}.reader_type, #{ReadMark.quoted_table_name}.reader_id, #{reader_class.quoted_table_name}.#{reader_class.quoted_primary_key}").
34
- having("COUNT(#{ReadMark.quoted_table_name}.id) > 1").
35
- select("#{reader_class.quoted_table_name}.#{reader_class.quoted_primary_key}")
33
+ reader_ids = ReadMark
34
+ .where(readable_type: readable_class.name, reader_type: reader_class.base_class.name)
35
+ .group(:reader_id)
36
+ .having('COUNT(*) > 1')
37
+ .select(:reader_id)
38
+
39
+ reader_class.reader_scope.where(reader_class.primary_key => reader_ids)
36
40
  end
37
41
 
38
42
  def update_read_marks_for_user(reader, timestamp)
39
43
  ReadMark.transaction do
40
44
  # Delete markers OLDER than the given timestamp
41
- reader.read_marks.
42
- where(readable_type: readable_class.name).
43
- single.
44
- older_than(timestamp).
45
- delete_all
45
+ reader.read_marks.where(readable_type: readable_class.name).single.older_than(timestamp).delete_all
46
46
 
47
47
  # Change the global timestamp for this reader
48
- rm = reader.read_mark_global(readable_class) || reader.read_marks.build
49
- rm.readable_type = readable_class.name
50
- rm.timestamp = timestamp - 1.second
51
- rm.save!
48
+ read_mark = reader.read_mark_global(readable_class) || reader.read_marks.build(readable_type: readable_class.name)
49
+ read_mark.update!(timestamp: timestamp - 1.second)
52
50
  end
53
51
  end
54
52
  end
@@ -0,0 +1,32 @@
1
+ module Unread
2
+ # Helpers for the gem itself. They are not part of the public API.
3
+ module Internal # :nodoc:
4
+ module_function
5
+
6
+ # The class that called acts_as_readable, also for STI subclasses
7
+ def readable_parent(klass)
8
+ klass.ancestors.find { |ancestor| ReadMark.readable_classes.include?(ancestor) }
9
+ end
10
+
11
+ def assert_reader_class!
12
+ raise 'There is no class using acts_as_reader.' if ReadMark.reader_classes.empty?
13
+ end
14
+
15
+ def assert_reader!(reader)
16
+ assert_reader_class!
17
+
18
+ unless ReadMark.reader_classes.any? { |klass| reader.is_a?(klass) }
19
+ raise ArgumentError, "Class #{reader.class.name} is not registered by acts_as_reader."
20
+ end
21
+ raise ArgumentError, 'The given reader has no id.' unless reader.id
22
+ end
23
+
24
+ def assert_readable!(readable)
25
+ unless readable.respond_to?(:mark_as_read!)
26
+ raise ArgumentError, "Class #{readable.class} is not registered by acts_as_readable."
27
+ end
28
+
29
+ raise ArgumentError, "The given #{readable.class} has no id." unless readable.id
30
+ end
31
+ end
32
+ end