diff --git a/static_comments.rb b/static_comments.rb index 86c00f2..5ad5be6 100644 --- a/static_comments.rb +++ b/static_comments.rb @@ -18,37 +18,43 @@ # 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 +Jekyll::Hooks.register :posts, :pre_render do |post, payload| + # code to call before Jekyll renders a post + id = payload["page"]["id"] + comments = StaticComments::find_for_post(payload["page"]["id"], payload["site"]["source"]) + payload["page"]["comments"] = comments + payload["page"]["comment_count"] = comments.length + payload["page"]["has_comments"] = (comments.length > 0) +end + +Jekyll::Hooks.register :site, :pre_render do |post, payload| + payload["site"]["posts"].each do |d| + comments = StaticComments::find_for_post(d.id, payload["site"]["source"]) + + d.data["comment_count"] = comments.length end 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, site) + @comments ||= read_comments(site) + @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) 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') comments[post_id] << yaml_data end - + comments end end