Sunspot で複雑な検索を行う場合、検索ブロックが長くなることがあります。
Post.search(include: [:author, :comments]) do # complex1 if complex_conditions1 with :blog_id, 1 else with(:published_at).less_than Time.now end # complex2 if complex_conditions2 with :author_id, 1 else with(:published_at).less_than_or_equal_to Time.now end end
search メソッドに、ブロック引数が渡されることを利用すると、以下のように書き直すことができます。
Post.search(include: [:author, :comments]) do |query| complex1 query complex2 query end def complex1(query) if complex_conditions1 query.with :blog_id, 1 else query.with(:published_at).less_than Time.now end end def complex2(query) if complex_conditions2 query.with :author_id, 1 else query.with(:published_at).less_than_or_equal_to Time.now end end