Sha256: d03628c7f32e9cc290add452bf767510f54b53b5b8c6617e34a58cea40936b28

Contents?: true

Size: 1.21 KB

Versions: 8

Compression:

Stored size: 1.21 KB

Contents

# frozen_string_literal: true

module Bridgetown
  # TODO: to be retired once the Resource engine is made official
  class RelatedPosts
    class << self
      attr_accessor :lsi
    end

    attr_reader :post, :site

    def initialize(post)
      @post = post
      @site = post.site
      if site.config.lsi
        Bridgetown::Utils::RequireGems.require_with_graceful_fail("classifier-reborn")
      end
    end

    def build
      return [] unless site.collections.posts.docs.size > 1

      if site.config.lsi
        build_index
        lsi_related_posts
      else
        most_recent_posts
      end
    end

    def build_index
      self.class.lsi ||= begin
        lsi = ClassifierReborn::LSI.new(auto_rebuild: false)
        Bridgetown.logger.info("Populating LSI...")

        site.collections.posts.docs.each do |x|
          lsi.add_item(x)
        end

        Bridgetown.logger.info("Rebuilding index...")
        lsi.build_index
        Bridgetown.logger.info("")
        lsi
      end
    end

    def lsi_related_posts
      self.class.lsi.find_related(post, 11) - [post]
    end

    def most_recent_posts
      @most_recent_posts ||= (site.collections.posts.docs.last(11).reverse - [post]).first(10)
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
bridgetown-core-0.21.5 lib/bridgetown-core/related_posts.rb
bridgetown-core-0.21.4 lib/bridgetown-core/related_posts.rb
bridgetown-core-0.21.3 lib/bridgetown-core/related_posts.rb
bridgetown-core-0.21.2 lib/bridgetown-core/related_posts.rb
bridgetown-core-0.21.1 lib/bridgetown-core/related_posts.rb
bridgetown-core-0.21.0 lib/bridgetown-core/related_posts.rb
bridgetown-core-0.21.0.beta4 lib/bridgetown-core/related_posts.rb
bridgetown-core-0.21.0.beta3 lib/bridgetown-core/related_posts.rb