ruby-on-railsrubyelasticsearchelasticsearch-ruby

How do I make ElasticSearch Client available application wide?


I am using elasticsearch_ruby within a Rails App. I chose not to use elasticsearch_rails because I do not want such tight integration with my ActiveRecord objects.

Using elasticsearch_ruby and elasticsearch_transport, a new client is created like this:

client = ElasticSearch::Client.new(log:true)

How do I make this client accessible application wide. I only want to create the instance once and then use it application wide.

What is the best practice for doing this?

It seems that there is something obvious that I'm missing.


Solution

  • Use an initializer
    1. Create a file under configuration/initializer/elasticsearch.rb
    2. Initialize your client like $elasticsearch_client=ElasticSearch::Client.new(log:true)
    3. Use this $elasticsearch_client anywhere in your rails app