From 77941d5cbf2e323a240052c795e28f8f881c4551 Mon Sep 17 00:00:00 2001 From: Mark Nottingham Date: Mon, 15 Feb 2016 15:14:21 +1100 Subject: [PATCH] Notice new files with watch; work with incremental with compatibility for 3.0+ from #18 --- static_comments.rb | 51 ++++++++++++++++++++++++++++------------------ 1 file changed, 31 insertions(+), 20 deletions(-) diff --git a/static_comments.rb b/static_comments.rb index 86c00f2..cbe2766 100644 --- a/static_comments.rb +++ b/static_comments.rb @@ -18,37 +18,48 @@ # You should have received a copy of the GNU General Public License along # with this program; if not, see -class Jekyll::Post - alias :to_liquid_without_comments :to_liquid - - def to_liquid(*args) - data = to_liquid_without_comments(*args) - data['comments'] = StaticComments::find_for_post(self) - data['comment_count'] = data['comments'].length - data - end +Jekyll::Hooks.register :site, :post_read do |site| + StaticComments::read_comments(site) + + site.posts.docs.each do |post| + comments = StaticComments::find_for_post(post.id) + comments.each do |comment| + comment_path = comment["path"] + site.regenerator.add_dependency(post.path, comment_path) + end + end +end + +Jekyll::Hooks.register :posts, :pre_render do |post, payload| + id = payload["page"]["id"] + comments = StaticComments::find_for_post(payload["page"]["id"]) + payload["page"]["comments"] = comments + payload["page"]["comment_count"] = comments.length + payload["page"]["has_comments"] = (comments.length > 0) end module StaticComments # Find all the comments for a post - def self.find_for_post(post) - @comments ||= read_comments(post.site.source) - @comments[post.id] + def self.find_for_post(post_id) + @comments[post_id] end - - # Read all the comments files in the site, and return them as a hash of - # arrays containing the comments, where the key to the array is the value - # of the 'post_id' field in the YAML data in the comments files. - def self.read_comments(source) + + def self.read_comments(site) + source = site.source comments = Hash.new() { |h, k| h[k] = Array.new } - + Dir["#{source}/**/_comments/**/*"].sort.each do |comment| next unless File.file?(comment) and File.readable?(comment) yaml_data = YAML::load_file(comment) post_id = yaml_data.delete('post_id') + yaml_data["path"] = comment comments[post_id] << yaml_data end - - comments + + comments.each_key do |key| + comments[key].sort!{|a,b| a['date'] <=> b['date'] } + end + + @comments = comments end end