zenet_logo

-株式会社ゼネット技術ブログ-

Rubyを3.1.2にバージョンアップしたらElasticsearch5.1.0がエラーとなったときの対処法

システム事業部の石黒です。
先日Ruby2.7.6からRuby 3.1.2にバージョンアップを行ったところ、elasticsearch-railsがエラーを吐きました。
その対応の備忘録になります。  

環境

  • rails 6.1.6.1
  • ruby 3.1.2
  • elasticsearch-rails 5.1.0

現象

このようなエラーを吐きました。(一部抜粋)

wrong number of arguments (given 1, expected 0)
/usr/local/bundle/gems/activerecord-6.1.6.1/lib/active_record/relation/batches.rb:128:in `find_in_batches’
/usr/local/bundle/gems/elasticsearch-model-5.1.0/lib/elasticsearch/model/adapters/active_record.rb:105:in `__find_in_batches’
/usr/local/bundle/gems/elasticsearch-model-5.1.0/lib/elasticsearch/model/importing.rb:122:in `import’

原因 

ruby 3から、キーワード引数が分離された(※1)ことによるエラーのようです。

対応 

あまり好ましくはないですが、今回はelasticsearch-railsのバージョンをあげることを避ける選択をしたため、モンキーパッチを当てることにしました。
elasticsearch-model6系、7系では修正されている(※2, ※3)ので、elasticsearch-railsのバージョンを上げることができる場合は上げたほうが良いと思います。

修正内容は下記になります。(※2と※3のPRの内容と同じ対応)  

# elasticsearch-model/lib/elasticsearch/model/adapters/active_record.rb
 
def __find_in_batches(options={}, &block)
 scope = scope.__send__(named_scope) if named_scope
 scope = scope.instance_exec(&query) if query
 
- scope.find_in_batches(options) do |batch|
+ scope.find_in_batches(**options) do |batch|
 yield (preprocess ? self.__send__(preprocess, batch) : batch)
 end

 

感想

古いバージョンと新しいバージョンの組み合わせは参考にできるものが少なくて調べるのが大変でした。

参考

※1) https://bugs.ruby-lang.org/issues/14183
※2) https://github.com/elastic/elasticsearch-rails/pull/952
※3) https://github.com/elastic/elasticsearch-rails/pull/937