Sha256: 58377c53d80304426ce3590a62b70ecf590da6e3f23a95aa1f71ceb04059b9f3

Contents?: true

Size: 1.78 KB

Versions: 8

Compression:

Stored size: 1.78 KB

Contents

module ElocalApiSupport
  module Actions
    module Index
      def index
        add_pagination_headers \
          if paginated_request? && paginate_with_headers?

        render_filtered_objects_as_json
      end

      protected

      def require_pagination?
        true
      end

      # Her library likes to paginate with headers,
      # ActiveResource cannot handle headers.
      # So awesomely, two implementations. To use the "Her" implementation with headers
      # this method should be overridend to return true
      def paginate_with_headers?
        false
      end

      private

      def render_paginated_results_without_headers
        render json: {
          current_page:  current_page,
          per_page:      paginated_request? ? per_page : filtered_objects.total_count,
          total_entries: filtered_objects.total_count,
          total_pages:   paginated_request? ? filtered_objects.total_pages : 1,
          records:       filtered_objects_for_json
        }
      end

      def render_paginated_results_with_headers
        render json: filtered_objects_for_json
      end

      def render_filtered_objects_as_json
        if paginate_with_headers?
          render_paginated_results_with_headers
        else
          render_paginated_results_without_headers
        end
      end

      def add_pagination_headers
        logger.debug { format 'Adding pagination headers for filtered_objects collection of size %d', filtered_objects.total_count }
        response.headers['x-total'] = filtered_objects.total_count.to_s
        response.headers['x-per-page'] = per_page.to_s
        response.headers['x-page'] = current_page.to_s
      end

      def paginated_request?
        require_pagination? || params[:page].present? || params[:per_page].present?
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
elocal_api_support-1.3.0 lib/elocal_api_support/actions/index.rb
elocal_api_support-1.2.0 lib/elocal_api_support/actions/index.rb
elocal_api_support-1.1.0 lib/elocal_api_support/actions/index.rb
elocal_api_support-1.0.0 lib/elocal_api_support/actions/index.rb
elocal_api_support-0.1.10 lib/elocal_api_support/actions/index.rb
elocal_api_support-0.1.9 lib/elocal_api_support/actions/index.rb
elocal_api_support-0.1.8 lib/elocal_api_support/actions/index.rb
elocal_api_support-0.1.7 lib/elocal_api_support/actions/index.rb