algolia / algoliasearch-rails

AlgoliaSearch integration to your favorite ORM
MIT License
409 stars 119 forks source link

Is it possible to use an add_index block in a concern? #423

Closed duhaime closed 2 years ago

duhaime commented 2 years ago

We have a few Rails models that all use an add_index block with identical configuration to store heterogenous models in a shared search index. We'd like to factor that config and the add_index block into a model concern. Is this possible? Any pointers others can offer on how to achieve this would be greatly appreciated!

rails version: 5.2.6.2 algoliasearch-rails version: 1.24.1 algoliasearch Version: 1.27.5 ruby 2.6.8p205

duhaime commented 2 years ago

It turns out one can use a Proc block to factor shared index logic into a concern, e.g.

shared_attributes = Proc.new do
  attribute(:title) { try(:title) }
  attribute(:body) { try(:body) }
  attribute(:type) { try(:type) }

  searchableAttributes %w{title body}
  attributesForFaceting [:type]
end

algoliasearch index_name: "Books_#{Rails.env}", sanitize: true, force_utf8_encoding: true do
  self.instance_eval &shared_attributes

  add_index "Articles_#{Rails.env}", if: :public? do
    self.instance_eval &shared_attributes
  end
end

def public?
  true
end