Using a decorator is a more elaborate approach than most people would use, and leads to a complicated calling syntax. I would do it like this:
module TextSearchSupport
def text_search(*args)
search_term = if args.last.responds_to(:[]) then args.pop[:query] end
query =
if search_term
where(args.map { |arg| "#{arg} @@ :q" }.join(' or '), q: query)
else
scoped
end
query.order(updated_at: :desc)
end
end
and extend TextSearchSupport
in each model that needs it. Then you can just call text_search('foo', 'bar', query: 'query') on the model.
A couple of asides:
- it is nicer to handle any number of fields rather than hardcoding, so I did that
- I think you want
scoped
rather thanall
to avoid running the query right away, so I used that, but you say your version was working so not sure what was going on there.