Skip to content
This repository was archived by the owner on Feb 19, 2025. It is now read-only.

Commit d51afe9

Browse files
committedJul 26, 2018
fix(dates): Tries to parse string dates in collection
1 parent a5bf8f6 commit d51afe9

File tree

2 files changed

+36
-3
lines changed

2 files changed

+36
-3
lines changed
 

‎lib/jekyll/algolia/file_browser.rb

+12-1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
require 'algolia_html_extractor'
44
require 'pathname'
5+
require 'time'
56

67
module Jekyll
78
module Algolia
@@ -234,14 +235,24 @@ def self.categories(file)
234235
def self.date(file)
235236
# Collections get their date from .date, while pages read it from .data.
236237
# Jekyll by default will set the date of collection to the current date,
237-
# but we overwrote this.
238+
# but we monkey-patched that so it returns nil for collection items
238239
date = if file.respond_to?(:date)
239240
file.date
240241
else
241242
file.data['date']
242243
end
243244

244245
return nil if date.nil?
246+
247+
# If date is a string, we try to parse it
248+
if date.is_a? String
249+
begin
250+
date = Time.parse(date)
251+
rescue StandardError
252+
return nil
253+
end
254+
end
255+
245256
date.to_time.to_i
246257
end
247258

‎spec/jekyll/algolia/file_browser_spec.rb

+24-2
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
# frozen_string_literal: true
22

3+
# rubocop:disable Metrics/BlockLength
34
require 'spec_helper'
45

5-
# rubocop:disable Metrics/BlockLength
66
describe(Jekyll::Algolia::FileBrowser) do
77
let(:current) { Jekyll::Algolia::FileBrowser }
88
let(:configurator) { Jekyll::Algolia::Configurator }
@@ -520,11 +520,33 @@
520520
let(:filepath) { 'sample-item.md' }
521521
it { should eq nil }
522522
end
523-
describe 'date in frontmatter' do
523+
describe 'date in frontmatter as DD-MM-YYYY' do
524524
let(:filepath) { 'collection-item.md' }
525525
it { should eq 452_469_600 }
526526
end
527527
end
528+
529+
# Sometimes a conjunction of plugins on the user side can change the format
530+
# of the date (it should be passed as a date object) and keep it as
531+
# a string. In order to test those cases, we will manually pass strings to
532+
# the call
533+
context 'direct call' do
534+
subject { current.date(file) }
535+
536+
let(:file) { double('File') }
537+
before do
538+
allow(file).to receive(:data).and_return(mock_data)
539+
end
540+
541+
describe 'date as a valid string' do
542+
let(:mock_data) { { 'date' => '1984-05-04' } }
543+
it { should eq 452_469_600 }
544+
end
545+
describe 'date as a invalid string' do
546+
let(:mock_data) { { 'date' => 'azertyuiop' } }
547+
it { should eq nil }
548+
end
549+
end
528550
end
529551

530552
describe '.excerpt_raw' do

0 commit comments

Comments
 (0)
Failed to load comments.