Last Updated: February 25, 2016
·
2.416K
· otobrglez

RSpec Rails helper for cleaning ElasticSearch index

There comes time when you want to clean ElasticSearch index related to your ActiveRecord models... This is simple RSspec method that will do the job for you...

 def clean_es! klass=nil
  if klass.nil?
    Dir[Rails.root.join("app","models","*.rb")].each do |m_p|
      begin
        klass_n = File.basename(m_p).sub(/.rb$/, '').classify.constantize
      rescue Exception => e
      end

      clean_es!(klass_n) unless klass.nil?
    end
    else
      if klass.ancestors.include? Tire::Model::Search
        klass.tire.index.delete
        klass.tire.create_elasticsearch_index
      end
    end
end