Sha256: 39a34f0791add3435e5735bfab001ef5e17c7e34fb9757724d50895ebdc9e8a0

Contents?: true

Size: 1.35 KB

Versions: 2

Compression:

Stored size: 1.35 KB

Contents

# frozen_string_literal: true

require 'pagy' if Gem.loaded_specs.has_key?('pagy')

module Macros
  class Search
    class Query < Macros::Base
      include Pagy::Backend if defined?(Pagy)

      # @return [Macros::Search::Results] step macro instance
      #
      # @example searchable is optional, paginate is true by default
      #   Macros::Search::Query(searchable: Admin)
      def initialize(searchable:, paginate: true)
        @searchable = searchable
        @paginate = paginate
      end

      # @param ctx [Trailblazer::Skill] tbl context hash
      #
      # The search params are passed in ctx[:params] and look like this:
      # `{q: 'the query', page: 2}`
      #
      # The orders is passed in ctx[:order] and looks like this:
      # `{created_at: :desc}`
      def call(ctx, params:, order: nil, **)
        return false unless @searchable

        ctx[:searchable] = @searchable

        ransack_search = @searchable.ransack params[:q]
        ctx[:query] = ransack_search

        temp_search_results = ransack_search.result

        if @paginate
          page = params[:page] || 1
          pagy, records = pagy(temp_search_results, page: page)
          ctx[:pages] = pagy
          temp_search_results = records
        end

        ctx[:search_results] = order ? temp_search_results.order(order) : temp_search_results
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
ff-tbl-macros-2.0.2 lib/macros/search/query.rb
ff-tbl-macros-2.0.1 lib/macros/search/query.rb