jekyll-better-related 0.1.0 → 0.2.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: d33886e0039dce0880cdfe899eba88e942d7e6c757ff001bf5f80a3541f1dca2
4
- data.tar.gz: 9fcb3ab8f7fbaa9392e37475538ce8420bf9449751144e4b9c863db1d59d4a36
3
+ metadata.gz: fc508ea07595817355c85c7e96a67b8f298cf9b644ea311189554a4d2157b6cd
4
+ data.tar.gz: 7bdc72bb09e793c4d93404a0e49ef5c6894b437a89439274abc768999b8aa635
5
5
  SHA512:
6
- metadata.gz: 8da0057c3d2569f6ed75b0e5702dee8439385b331244114e4aa8802fee0af0edd275123b8c07ba202722158dacf9233022bd6b6f07b70093719daf04f01e8217
7
- data.tar.gz: 8978d32da133a5dcf9ba1f828ab4447c56f2127e47db817b25954ee76ba16d20c68794f34ab5ea7f73d311b732c747c1ddf49fb6d7be3481085a2c31c45268e4
6
+ metadata.gz: 374e3bce48997eeb06fe0efb6b0aab4d94d856ed633f43e41e6fff57e3fbccc928d98e853bfd850838d9aee6dcafc752416c8d315518516670c6f349bbd6cabe
7
+ data.tar.gz: 451435f760ea87d4e7324564f06e65d8c56c52444aa72d84eca5b0113672d2bd92eaa8ce7c2fdc0707880a60e4dd53a27764595c01d67ace9e9adebd4ff4c09c
data/CHANGELOG.md CHANGED
@@ -2,6 +2,27 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## [0.2.0] - 2026-11-28
6
+
7
+ ### Fixed
8
+ - Numeric and boolean front matter values in `tags`, `categories` and `category` (for example `tags: [2024]` or `tags: [yes]`) no longer raise `NoMethodError` and fail the build. Values are converted to text; nil and blank entries are ignored.
9
+ - Related lists are now ordered by score, then date (newest first), then URL, so ties come out the same on every build.
10
+ - `cross_collection: true` skips collections with `output: false`, which have no pages to link to.
11
+ - Manual `related_posts:` overrides now resolve against the same documents the scorer uses (including cross-collection ones), accept URLs with or without a trailing slash, and log a warning for entries that match nothing.
12
+ - Title keywords are Unicode-aware, so non-ASCII titles (accents, Cyrillic, CJK) now contribute to scores. Titles with accented letters tokenise differently than before.
13
+ - Added the missing `require "set"`.
14
+
15
+ ### Changed
16
+ - Scoring is much faster. Tags, categories, keywords and dates are computed once per document, and an inverted index means only posts that share a term are scored. In a benchmark with 850 posts, build time for the plugin went from 6.3 to 6.8 s down to 0.1 to 0.35 s depending on how much the posts' tags overlap.
17
+ - **Behaviour change:** the recency penalty is now capped at 1.0 point by default (new `max_recency_penalty` option). Previously it was unbounded, so a post sharing one tag fell below the default `min_score` of 1 after about 20 months. Results can change for sites with older posts. Set `max_recency_penalty: false` to restore the 0.1.0 behaviour.
18
+ - Raised the minimum Ruby version to 3.0.
19
+ - README now documents the real defaults (`count` is 3), says that `page.related_posts` stays `false` for opted-out posts and is unset on non-posts, and says the plugin does not replace `site.related_posts`. The gemspec description no longer calls it a drop-in replacement.
20
+
21
+ ### Added
22
+ - `max_recency_penalty` option.
23
+ - `Rakefile` (`bundle exec rake` runs the tests) and a GitHub Actions workflow for Ruby 3.1, 3.2 and 3.3.
24
+ - Tests: non-string front matter, penalty cap, tie order, collections, overrides, Unicode titles, and a comparison against a naive reference scorer on synthetic posts.
25
+
5
26
  ## [0.1.0] - 2026-08-20
6
27
 
7
28
  ### Added
data/README.md CHANGED
@@ -1,12 +1,12 @@
1
1
  # jekyll-better-related
2
2
 
3
- A Jekyll plugin that replaces Jekyll's useless built-in related posts (which just returns the most recent posts) with a proper relevance-scored algorithm.
3
+ A Jekyll plugin that scores your posts against each other and gives each post a list of related posts. Jekyll's built-in `site.related_posts` just returns the most recent posts, and this plugin gives you something better to use in its place.
4
4
 
5
5
  [![Gem Version](https://badge.fury.io/rb/jekyll-better-related.svg)](https://rubygems.org/gems/jekyll-better-related)
6
6
 
7
7
  ## Why?
8
8
 
9
- Jekyll's `site.related_posts` is just the N most recently published posts — it has nothing to do with the current post's content. `jekyll-better-related` scores every candidate post on shared tags, categories, and title keywords, with a small recency penalty, so readers actually get posts that are relevant to what they're reading.
9
+ Jekyll's `site.related_posts` is just the N most recently published posts. It has nothing to do with the current post's content. `jekyll-better-related` scores every candidate post on shared tags, categories, and title keywords, with a small recency penalty, so readers get posts that are relevant to what they're reading. The plugin sets `page.related_posts`. It leaves `site.related_posts` alone, so a theme that reads `site.related_posts` keeps showing the recent-posts list until you change it to `page.related_posts`.
10
10
 
11
11
  ## How It Scores
12
12
 
@@ -15,9 +15,11 @@ Jekyll's `site.related_posts` is just the N most recently published posts — it
15
15
  | Shared tag | +3 per tag |
16
16
  | Shared category | +2 |
17
17
  | Shared title keyword | +1 per word |
18
- | Age difference | −0.1 per 30 days |
18
+ | Age difference | −0.1 per 30 days, capped (see `max_recency_penalty`) |
19
19
 
20
- Tags and categories are matched case-insensitively. Common English stop words are excluded from keyword scoring.
20
+ Tags and categories are matched case-insensitively, and numbers or booleans in front matter (`tags: [2024]`) are treated as text. Blank values are ignored. Title keywords can be in any language. Common English stop words and words under three characters are excluded.
21
+
22
+ Results are ordered by score, then by date (newest first), then by URL, so a build always gives the same lists.
21
23
 
22
24
  ## Installation
23
25
 
@@ -40,11 +42,16 @@ All settings are optional. Defaults are shown:
40
42
 
41
43
  ```yaml
42
44
  better_related:
43
- count: 5 # max related posts to surface
44
- min_score: 1 # minimum relevance score; 0 disables threshold
45
- cross_collection: false # include posts from other collections
45
+ count: 3 # max related posts to surface
46
+ min_score: 1 # minimum relevance score; 0 disables threshold
47
+ cross_collection: false # include documents from other collections
48
+ max_recency_penalty: 1.0 # most points the age difference can subtract
46
49
  ```
47
50
 
51
+ `max_recency_penalty` stops old posts from falling out of the results just because they're old. At 1.0, two posts that share one tag (3 points) always score at least 2, so they pass the default `min_score` of 1 at any age. Set it to `false` to remove the cap, which is how 0.1.0 behaved: without it, one shared tag stopped qualifying after about 20 months.
52
+
53
+ `cross_collection` only pulls in collections that have `output: true`, since documents in other collections have no page to link to. Only posts get a `related_posts` list.
54
+
48
55
  ## Template Usage
49
56
 
50
57
  The plugin injects results into `page.related_posts` for every post. Use it in your layout:
@@ -60,7 +67,7 @@ The plugin injects results into `page.related_posts` for every post. Use it in y
60
67
  {% endif %}
61
68
  ```
62
69
 
63
- `page.related_posts` is always an Array (may be empty), so checking `.size > 0` before rendering is safe.
70
+ For a post that gets scored, `page.related_posts` is an Array and may be empty. For a post with `related_posts: false` it stays `false`, and on pages that aren't posts it isn't set. The `{% if page.related_posts and page.related_posts.size > 0 %}` check above covers all three.
64
71
 
65
72
  ## Per-Post Frontmatter Options
66
73
 
@@ -72,7 +79,7 @@ related_posts: false
72
79
 
73
80
  ### Manual override
74
81
 
75
- Supply an explicit list of post URLs (relative to site root). The plugin resolves them from the site and skips scoring:
82
+ Supply an explicit list of URLs (relative to site root). The plugin looks them up among the same documents it scores, so a trailing slash is optional, and skips scoring. An entry that matches nothing is skipped with a warning in the build log:
76
83
 
77
84
  ```yaml
78
85
  related_posts:
@@ -80,6 +87,13 @@ related_posts:
80
87
  - /2024/02/another-post/
81
88
  ```
82
89
 
90
+ ## Development
91
+
92
+ ```bash
93
+ bundle install
94
+ bundle exec rake
95
+ ```
96
+
83
97
  ## GitHub Pages / Safe Mode
84
98
 
85
99
  This plugin uses a custom Generator and cannot run in GitHub Pages' safe mode. Use a CI/CD build step (GitHub Actions, Cloudflare Pages, etc.) to build and deploy.
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "set"
3
4
  require "jekyll"
4
5
 
5
6
  module Jekyll
@@ -15,6 +16,13 @@ module Jekyll
15
16
  RECENCY_PENALTY = 0.1
16
17
  SECONDS_PER_MONTH = 60 * 60 * 24 * 30
17
18
 
19
+ # Upper bound on the recency penalty, in points, used when the site does
20
+ # not set `max_recency_penalty`. With 1.0 a single shared tag (3 points)
21
+ # always stays above the default `min_score` of 1, however old the posts
22
+ # are. Set this to nil to make "no cap" the default again (the 0.1.0
23
+ # behaviour); sites can also opt out with `max_recency_penalty: false`.
24
+ DEFAULT_MAX_RECENCY_PENALTY = 1.0
25
+
18
26
  # Common English stop words to exclude from keyword matching
19
27
  STOP_WORDS = %w[
20
28
  a an the and or but in on at to for of with is are was were be been
@@ -24,96 +32,257 @@ module Jekyll
24
32
  all any each just like may my our own said such use your
25
33
  ].to_set.freeze
26
34
 
35
+ # Everything the scorer needs to know about one document, computed once.
36
+ Profile = Struct.new(:doc, :tags, :categories, :category, :keywords, :time, :url)
37
+
38
+ EMPTY = [].freeze
39
+
27
40
  def generate(site)
28
41
  @site = site
29
42
  @config = site.config["better_related"] || {}
43
+ @recency_cap = nil
30
44
 
31
45
  count = (@config["count"] || 3).to_i
32
46
  min_score = (@config["min_score"] || 1).to_f
33
47
 
34
- candidates = collect_candidates
48
+ build_pool
49
+ build_index
35
50
 
36
- site.posts.docs.each do |post|
51
+ site.posts.docs.each_with_index do |post, i|
37
52
  # Per-post manual override: list of URLs
38
53
  override = post.data["related_posts"]
39
54
  if override.is_a?(Array)
40
- post.data["related_posts"] = resolve_manual(override)
55
+ post.data["related_posts"] = resolve_manual(post, override)
41
56
  next
42
57
  end
43
58
 
44
59
  # Per-post opt-out
45
60
  next if override == false
46
61
 
47
- scored = candidates
48
- .reject { |c| c.equal?(post) }
49
- .map { |c| [c, score(post, c)] }
50
- .select { |_, s| s >= min_score }
51
- .sort_by { |_, s| -s }
52
- .first(count)
53
- .map(&:first)
54
-
55
- post.data["related_posts"] = scored
62
+ post.data["related_posts"] = top_related(i, count, min_score)
56
63
  end
57
64
  end
58
65
 
59
66
  private
60
67
 
68
+ # --- candidate pool -------------------------------------------------
69
+
61
70
  def collect_candidates
62
71
  docs = @site.posts.docs.dup
63
72
  if @config["cross_collection"]
64
73
  @site.collections.each_value do |col|
65
74
  next if col.label == "posts"
75
+ next unless outputs?(col)
66
76
  docs += col.docs
67
77
  end
68
78
  end
69
79
  docs
70
80
  end
71
81
 
72
- def score(post, candidate)
73
- s = 0.0
82
+ # Collections with `output: false` have no pages, so linking to their
83
+ # documents would produce dead links.
84
+ def outputs?(collection)
85
+ if collection.respond_to?(:write?)
86
+ collection.write?
87
+ elsif collection.respond_to?(:metadata)
88
+ collection.metadata["output"] ? true : false
89
+ else
90
+ true
91
+ end
92
+ end
93
+
94
+ def build_pool
95
+ @pool = collect_candidates
96
+ @profiles = @pool.map { |doc| profile_for(doc) }
97
+ @by_url = {}
98
+ @profiles.each { |pr| @by_url[normalize_url(pr.url)] ||= pr.doc }
99
+ end
100
+
101
+ # Inverted indexes: term => positions in the pool. Only documents that
102
+ # share at least one term with a post are ever scored.
103
+ def build_index
104
+ @tag_index = Hash.new { |h, k| h[k] = [] }
105
+ @cat_index = Hash.new { |h, k| h[k] = [] }
106
+ @category_index = Hash.new { |h, k| h[k] = [] }
107
+ @kw_index = Hash.new { |h, k| h[k] = [] }
108
+
109
+ @profiles.each_with_index do |pr, i|
110
+ pr.tags.each { |t| @tag_index[t] << i }
111
+ pr.categories.each { |t| @cat_index[t] << i }
112
+ @category_index[pr.category] << i if pr.category
113
+ pr.keywords.each { |t| @kw_index[t] << i }
114
+ end
115
+ [@tag_index, @cat_index, @category_index, @kw_index].each { |h| h.default_proc = nil }
116
+ end
117
+
118
+ # --- profiles ---------------------------------------------------------
119
+
120
+ def profile_for(doc)
121
+ data = doc.data
122
+ Profile.new(
123
+ doc,
124
+ normalize_list(data["tags"]),
125
+ normalize_list(data["categories"]),
126
+ normalize_scalar(data["category"]),
127
+ keywords(data["title"].to_s),
128
+ time_of(data["date"]),
129
+ doc.url
130
+ )
131
+ end
132
+
133
+ # Coerce front matter values to a set of lowercase strings. Numbers and
134
+ # booleans (`tags: [2024]`, `tags: [yes]`) become strings; nil and blank
135
+ # entries are ignored.
136
+ def normalize_list(value)
137
+ Array(value).flatten.each_with_object(Set.new) do |v, set|
138
+ s = normalize_scalar(v)
139
+ set << s if s
140
+ end
141
+ end
142
+
143
+ def normalize_scalar(value)
144
+ value = value.first if value.is_a?(Array)
145
+ return nil if value.nil?
146
+
147
+ s = value.to_s.strip.downcase
148
+ s.empty? ? nil : s
149
+ end
150
+
151
+ # Seconds since the epoch as an exact number (Integer when whole), so
152
+ # pairwise differences are cheap and give the same result as Time#-.
153
+ def time_of(date)
154
+ return nil unless date.respond_to?(:to_time)
155
+
156
+ r = date.to_time.to_r
157
+ r.denominator == 1 ? r.numerator : r
158
+ end
159
+
160
+ # --- scoring ----------------------------------------------------------
161
+
162
+ def top_related(index, count, min_score)
163
+ me = @profiles[index]
164
+ base = shared_term_scores(me)
74
165
 
75
- # Tag overlap
76
- post_tags = Array(post.data["tags"]).map(&:downcase)
77
- cand_tags = Array(candidate.data["tags"]).map(&:downcase)
78
- s += (post_tags & cand_tags).size * TAG_WEIGHT
166
+ # A candidate sharing nothing scores zero minus its recency penalty, so
167
+ # it can only qualify when min_score is not positive. Then scan all.
168
+ positions = min_score <= 0 ? (0...@profiles.size) : base.keys
79
169
 
80
- # Category match
81
- post_cats = Array(post.data["categories"]).map(&:downcase)
82
- cand_cats = Array(candidate.data["categories"]).map(&:downcase)
83
- s += (post_cats & cand_cats).size * CATEGORY_WEIGHT
170
+ top = [] # best first, at most `count` entries of [profile, score]
171
+ positions.each do |i|
172
+ next if i == index
84
173
 
85
- # Category singular field
86
- if post.data["category"] && candidate.data["category"]
87
- s += CATEGORY_WEIGHT if post.data["category"].downcase == candidate.data["category"].downcase
174
+ shared = base.fetch(i, 0)
175
+ next if shared < min_score # the penalty can only lower the score
176
+
177
+ cand = @profiles[i]
178
+ s = shared.to_f - recency_penalty(me, cand)
179
+ next if s < min_score
180
+
181
+ insert_ranked(top, cand, s, count)
182
+ end
183
+
184
+ top.map { |cand, _| cand.doc }
185
+ end
186
+
187
+ # Keep `top` sorted by score desc, then date desc, then URL, trimmed to
188
+ # `count` entries, without sorting every candidate.
189
+ def insert_ranked(top, cand, score, count)
190
+ return if count <= 0
191
+ return if top.size >= count && !ranks_before?(cand, score, *top.last)
192
+
193
+ pos = top.index { |other, other_score| ranks_before?(cand, score, other, other_score) } || top.size
194
+ top.insert(pos, [cand, score])
195
+ top.pop if top.size > count
196
+ end
197
+
198
+ def ranks_before?(cand, score, other, other_score)
199
+ return score > other_score if score != other_score
200
+
201
+ a = date_sort_key(cand)
202
+ b = date_sort_key(other)
203
+ return a < b if a != b
204
+
205
+ cand.url.to_s < other.url.to_s
206
+ end
207
+
208
+ # position => points from shared tags, categories and title keywords
209
+ def shared_term_scores(me)
210
+ scores = Hash.new(0)
211
+ me.tags.each { |t| (@tag_index[t] || EMPTY).each { |i| scores[i] += TAG_WEIGHT } }
212
+ me.categories.each { |t| (@cat_index[t] || EMPTY).each { |i| scores[i] += CATEGORY_WEIGHT } }
213
+ if me.category
214
+ (@category_index[me.category] || EMPTY).each { |i| scores[i] += CATEGORY_WEIGHT }
88
215
  end
216
+ me.keywords.each { |t| (@kw_index[t] || EMPTY).each { |i| scores[i] += KEYWORD_WEIGHT } }
217
+ scores
218
+ end
89
219
 
90
- # Title keyword overlap
91
- post_kw = keywords(post.data["title"].to_s)
92
- cand_kw = keywords(candidate.data["title"].to_s)
93
- s += (post_kw & cand_kw).size * KEYWORD_WEIGHT
94
-
95
- # Recency penalty
96
- post_date = post.data["date"]
97
- cand_date = candidate.data["date"]
98
- if post_date && cand_date
99
- months_apart = (post_date.to_time - cand_date.to_time).abs / SECONDS_PER_MONTH
100
- s -= months_apart * RECENCY_PENALTY
220
+ def recency_penalty(a, b)
221
+ return 0.0 unless a.time && b.time
222
+
223
+ months_apart = (a.time - b.time).abs.to_f / SECONDS_PER_MONTH
224
+ penalty = months_apart * RECENCY_PENALTY
225
+ cap = recency_cap
226
+ penalty > cap ? cap : penalty
227
+ end
228
+
229
+ def recency_cap
230
+ @recency_cap ||= begin
231
+ cfg = (@config || {})["max_recency_penalty"]
232
+ cfg = DEFAULT_MAX_RECENCY_PENALTY if cfg.nil?
233
+ if cfg == false || cfg.nil?
234
+ Float::INFINITY
235
+ else
236
+ [cfg.to_f, 0.0].max
237
+ end
101
238
  end
239
+ end
240
+
241
+ # Newer first; documents without a date sort last.
242
+ def date_sort_key(profile)
243
+ profile.time ? -profile.time : Float::INFINITY
244
+ end
102
245
 
103
- s
246
+ # Score of one pair, computed straight from the two profiles. The
247
+ # generator uses the inverted index instead; this is the same arithmetic
248
+ # and is kept for direct testing.
249
+ def score(post, candidate)
250
+ a = profile_for(post)
251
+ b = profile_for(candidate)
252
+
253
+ s = (a.tags & b.tags).size * TAG_WEIGHT
254
+ s += (a.categories & b.categories).size * CATEGORY_WEIGHT
255
+ s += CATEGORY_WEIGHT if a.category && a.category == b.category
256
+ s += (a.keywords & b.keywords).size * KEYWORD_WEIGHT
257
+
258
+ s.to_f - recency_penalty(a, b)
104
259
  end
105
260
 
106
261
  def keywords(title)
107
262
  title.downcase
108
- .gsub(/[^a-z0-9\s]/, " ")
263
+ .gsub(/[^\p{L}\p{M}\p{N}\s]/, " ")
109
264
  .split
110
265
  .reject { |w| STOP_WORDS.include?(w) || w.length < 3 }
111
266
  .to_set
112
267
  end
113
268
 
114
- def resolve_manual(urls)
269
+ # --- manual overrides ---------------------------------------------------
270
+
271
+ def normalize_url(url)
272
+ url.to_s.strip.sub(%r{/+\z}, "")
273
+ end
274
+
275
+ def resolve_manual(post, urls)
115
276
  urls.filter_map do |url|
116
- @site.posts.docs.find { |p| p.url == url }
277
+ found = @by_url[normalize_url(url)]
278
+ unless found
279
+ Jekyll.logger.warn(
280
+ "BetterRelated:",
281
+ "#{post.url}: related_posts entry #{url.inspect} does not match any " \
282
+ "published document, skipping it"
283
+ )
284
+ end
285
+ found
117
286
  end
118
287
  end
119
288
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module JekyllBetterRelated
4
- VERSION = "0.1.0"
4
+ VERSION = "0.2.0"
5
5
  end
metadata CHANGED
@@ -1,13 +1,13 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: jekyll-better-related
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0
4
+ version: 0.2.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Jason Chance
8
8
  bindir: bin
9
9
  cert_chain: []
10
- date: 2026-08-21 00:00:00.000000000 Z
10
+ date: 2026-11-29 00:00:00.000000000 Z
11
11
  dependencies:
12
12
  - !ruby/object:Gem::Dependency
13
13
  name: jekyll
@@ -29,9 +29,10 @@ dependencies:
29
29
  - - "<"
30
30
  - !ruby/object:Gem::Version
31
31
  version: '5.0'
32
- description: jekyll-better-related replaces Jekyll's built-in related_posts (which
33
- is just recency) with a proper relevance scorer using tag overlap, category match,
34
- and title keyword overlap. Drop-in replacement — no theme changes required.
32
+ description: jekyll-better-related scores every post against the others on shared
33
+ tags, categories and title keywords, minus a capped recency penalty, and sets the
34
+ best matches as page.related_posts. It does not change Jekyll's built-in site.related_posts,
35
+ so layouts need to read page.related_posts.
35
36
  email:
36
37
  - jason@jasonchance.com
37
38
  executables: []
@@ -58,7 +59,7 @@ required_ruby_version: !ruby/object:Gem::Requirement
58
59
  requirements:
59
60
  - - ">="
60
61
  - !ruby/object:Gem::Version
61
- version: 2.7.0
62
+ version: '3.0'
62
63
  required_rubygems_version: !ruby/object:Gem::Requirement
63
64
  requirements:
64
65
  - - ">="
@@ -67,5 +68,5 @@ required_rubygems_version: !ruby/object:Gem::Requirement
67
68
  requirements: []
68
69
  rubygems_version: 3.6.2
69
70
  specification_version: 4
70
- summary: Relevance-scored related posts for Jekyll — because the built-in is useless.
71
+ summary: Relevance-scored related posts for Jekyll, available as page.related_posts.
71
72
  test_files: []