mardi 2 mars 2021

Rails - Controller DRY - Generic way of doing common filtering/sorting/pagination

Developing a new API, I noticed I will be repeating the same code across multiple indexes, Trying to avoid this, but not sure on the best method?

current scenario:

books_controller

        def index
          books = Book.filtered(query_params).sorted(sorting_params)
          .page(pagination_params[:page])
          .per(pagination_params[:per_page])
          #.includes(:author) // placeholder for dynamic includable associations

          json_response(BooksSerializer.new(books).as_json)
        end

Initial Idea I had, was creating ResourcesService, that would receive a model, for example Book class, and from there apply the methods (filtered, sorted..pagination) and return an ActiveRecord_Relation object to be serialized and returned.

Not sure on how to write it though (as a PORO or Module)

Any tips, on how to make this DRY and reusable across controllers?

Archieving something like, to reproduce on other controllers:

books = ResourceService.new(Book, query_params, sorting_params, pagination_params, includables)

Aucun commentaire:

Enregistrer un commentaire