Skip to content

Instantly share code, notes, and snippets.

@frankie-loves-jesus
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frankie-loves-jesus/5567dd87c3338d23483b to your computer and use it in GitHub Desktop.
Save frankie-loves-jesus/5567dd87c3338d23483b to your computer and use it in GitHub Desktop.
Forem with PgSearch + Google-like stats

Forem with PgSearch + Google-like stats

Based on this working Forem + PgSearch example:

Live app:

Run /etc/init.d/postgresql start before hitting the Run button.

app/views/forem/forums/search.html.erb

<p>About <%= @rough_count %> results (<%= @duration.round(2) %> seconds)</p>

app/decorators/models/forem/topic_decorator.rb

Forem::Topic.class_eval do
  include PgSearch

  require 'benchmark'

  pg_search_scope :search, against: [:subject], using: { tsearch: { dictionary: "english" } }, associated_against: { posts: [:text] }

  module ResultsCount
    def rough_count(count)
      rounded_digits = String(count).size / 2
      rounding_factor = 10 ** rounded_digits

      (Integer(count) / rounding_factor) * rounding_factor 
    end
  end 
end 

app/decorators/controllers/forem/topics_controller_decorator.rb

Forem::ForumsController.class_eval do
  include ResultsCount

  def search
    @search = params[:keywords]
    @topics = Forem::Topic.search(@search)

    @duration = Benchmark.realtime do
      @scope = PgSearch.multisearch(@search)
      @results = @scope.page(params.fetch(:page, 1))
    end

    @rough_count = rough_count(@scope.count)
  end
end 

Output:

ActiveRecord::StatementInvalid in Forem::ForumsController#search
PG::UndefinedTable: ERROR: relation "pg_search_documents" does not exist LINE 5: WHERE a.attrelid = '"pg_search_documents"'::r... ^ : SELECT a.attname, format_type(a.atttypid, a.atttypmod), pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod FROM pg_attribute a LEFT JOIN pg_attrdef d ON a.attrelid = d.adrelid AND a.attnum = d.adnum WHERE a.attrelid = '"pg_search_documents"'::regclass AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment