Commit 030adf12 authored by Grzegorz Bizon's avatar Grzegorz Bizon

Encapsulate reused pagination component in a class

parent ac060701
...@@ -7,12 +7,20 @@ class EnvironmentSerializer < BaseSerializer ...@@ -7,12 +7,20 @@ class EnvironmentSerializer < BaseSerializer
tap { @itemize = true } tap { @itemize = true }
end end
def with_pagination(request, response)
tap { @paginator = Paginator.new(request, response) }
end
def itemized? def itemized?
@itemize @itemize
end end
def paginated?
defined?(@paginator)
end
def represent(resource, opts = {}) def represent(resource, opts = {})
# resource = paginate(resource) if paginated? resource = @paginator.paginate(resource) if paginated?
if itemized? if itemized?
itemize(resource).map do |item| itemize(resource).map do |item|
......
class Paginator
include API::Helpers::Pagination
def initialize(request, response)
@request = request
@response = response
end
private
# Methods needed by `API::Helpers::Pagination`
#
attr_reader :request
def params
@request.query_parameters
end
def header(header, value)
@response.headers[header] = value
end
end
class PipelineSerializer < BaseSerializer class PipelineSerializer < BaseSerializer
class InvalidResourceError < StandardError; end class InvalidResourceError < StandardError; end
include API::Helpers::Pagination
Struct.new('Pagination', :request, :response)
entity PipelineEntity entity PipelineEntity
def with_pagination(request, response)
tap { @paginator = Paginator.new(request, response) }
end
def paginated?
defined?(@paginator)
end
def represent(resource, opts = {}) def represent(resource, opts = {})
if paginated? if paginated?
raise InvalidResourceError unless resource.respond_to?(:page) raise InvalidResourceError unless resource.respond_to?(:page)
super(paginate(resource.includes(project: :namespace)), opts) resource = resource.includes(project: :namespace)
super(@paginator.paginate(resource), opts)
else else
super(resource, opts) super(resource, opts)
end end
end end
def paginated?
defined?(@pagination)
end
def with_pagination(request, response)
tap { @pagination = Struct::Pagination.new(request, response) }
end
private
# Methods needed by `API::Helpers::Pagination`
#
def params
@pagination.request.query_parameters
end
def request
@pagination.request
end
def header(header, value)
@pagination.response.headers[header] = value
end
end end
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment