Skip to content

Instantly share code, notes, and snippets.

@xenda
Forked from anonymous/entries_controller.rb
Last active December 10, 2015 20:08
Show Gist options
  • Save xenda/4486522 to your computer and use it in GitHub Desktop.
Save xenda/4486522 to your computer and use it in GitHub Desktop.
class Entry < ActiveRecord::Base
ITEMS_PER_PAGE = 50
belongs_to :subreddit
def self.page_for(subreddit, page)
if subreddit
entries = subreddit.entries
else
entries = Entry.all
end
pages, extra = entries.count.divmod(ITEMS_PER_PAGE)
pages += 1 if extra > 0
page = 1 if page < 1
skip = (page - 1) * ITEMS_PER_PAGE
data = entries.limit(ITEMS_PER_PAGE).offset(skip).order("id DESC")
next_page = page < pages ? page + 1 : page
prev_page = page > 1 ? page - 1 : page
next_page = "/entries/?page=#{next_page}"
prev_page = "/entries/?page=#{prev_page}"
{page: page, next: next_page, prev: prev_page, data: data}
end
end
class EntriesController < ApplicationController
def index
subreddit = Subreddit.find(params[:subreddit)
if subreddit
render json: Entry.page_for(subreddit, params[:page])
else
#something bad
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment