Last active
May 22, 2019 21:16
-
-
Save eebs/41475f983f0822edbf11a1be4bedf91f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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