Skip to content

Instantly share code, notes, and snippets.

@eebs
Last active May 22, 2019 21:16
Show Gist options
  • Save eebs/41475f983f0822edbf11a1be4bedf91f to your computer and use it in GitHub Desktop.
Save eebs/41475f983f0822edbf11a1be4bedf91f to your computer and use it in GitHub Desktop.
class PostsController < ApiController
def index
posts = policy_scope([:api, Post.all])
paginator = Paginator.new(posts, params[:page])
render json: PostSerializer.new(
paginator.paginated_relation,
meta: {
total_count: paginator.total_count,
},
)
end
end
class PagedStrategy
def initialize(params = nil)
parse_params(params)
# raise on invalid values here
end
def apply(relation)
offset = (number - 1) * size
relation.offset(offset).limit(size)
end
private
attr_reader :number, :size
def parse_params(params)
case params
when NilClass
@number = 1
@size = default_page_size
when ActionController::Parameters
params = params.permit(:number, :size)
@number = params.fetch(:number, 1).to_i
@size = params.fetch(:size, default_page_size).to_i
when Hash
@number = params.fetch(:number, 1).to_i
@size = params.fetch(:size, default_page_size).to_i
end
end
def default_page_size
25
end
end
class Paginator
def initialize(relation:, page:)
@relation = relation
@page = page
end
def paginated_relation
strategy.apply(relation)
end
def total_count
relation.count
end
private
attr_reader :relation, :page
def strategy
@strategy ||= PagedStrategy.new(page)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment