Sha256: 38831615fb3e0dc25edf0a9b551ea72a7afe281e6e315ce94e54bbce0678e301

Contents?: true

Size: 1.06 KB

Versions: 1

Compression:

Stored size: 1.06 KB

Contents

module BrilliantCms
  module Concerns
    module Searchable
      extend ActiveSupport::Concern

      included do
        has_many :search_data, class_name: 'BrilliantCms::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, brilliant_cms_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
        BrilliantCms::EntrySearchData.index_entry_data(id, search_attributes)
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
brilliant_cms-0.0.1 app/models/brilliant_cms/concerns/searchable.rb