Sha256: 5d867c520ae4541481869905f58249d9c1e3a0b2ccf74d01bc37d16e89e5c002

Contents?: true

Size: 1.05 KB

Versions: 2

Compression:

Stored size: 1.05 KB

Contents

module Plotline
  module Concerns
    module Searchable
      extend ActiveSupport::Concern

      included do
        has_many :search_data, class_name: 'Plotline::EntrySearchData'

        after_save :update_search_index
      end

      module ClassMethods
        def searchable_attributes(*args)
          @searchable_attributes = args if args.any?
          @searchable_attributes ||= []
        end

        def search(query)
          select('DISTINCT ON (entry_id) entry_id, plotline_entries.*').
            joins(:search_data).
            where("search_data @@ plainto_tsquery('english', :q)", q: query).
            order("entry_id, ts_rank(search_data, plainto_tsquery('%s')) desc" % send(:sanitize_sql, query))
        end
      end

      def search_attributes
        self.class.searchable_attributes.each_with_object({}) do |attr_name, search_data|
          search_data[attr_name] = send(attr_name)
        end
      end

      def update_search_index
        Plotline::EntrySearchData.index_entry_data(id, search_attributes)
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
plotline-0.1.1 app/models/plotline/concerns/searchable.rb
plotline-0.1.0 app/models/plotline/concerns/searchable.rb