Twitter Updates

Saturday, 6 February 2010

Sinartra limit blog posts displayed on a page

To limit the number of database elements returned in ActiveRecord is trivial but there is a little bit of work involved with getting the links setup to jump forward and backwards.

I have decided to use these [1,2,3] URLs to navigate the list of blog posts
[1] /blog : always the latest
[2] /blog/older : The next page of blog posts
[3] /blog/older/integer : a page of blog posts starting at integer the links provided will increment this by a fixed amount, but the route can accept any value.

NB: as allways I have inserted some extra space in to the code to get it to display rather than render, you may have to delete spaces after <.

My app.rb:
require 'rubygems'
require 'sinatra'
require 'active_record'

$blogpath = "blog"
$blogs_per_page = 10

:adapter => 'sqlite3',
:database => './db/blog.db'

class Posts < ActiveRecord::Base

get '/blog/?' do
@offset = 0
@posts = Posts.find(:all, :order => "id DESC", :limit => $blogs_per_page)
erb :'blog/all'

get '/blog/older/?' do
#This probably should be a redirect to /blog/older/$blogs_per_page
@offset = $blogs_per_page
@posts = Posts.find(:all, :order => "id DESC", :limit => $blogs_per_page, :offset => @offset)
erb :'blog/all'

get '/blog/older/:offset/?' do
@offset = params[:offset].to_i
@posts = Posts.find(:all, :order => "id DESC", :limit => $blogs_per_page, :offset => @offset)
erb :'blog/all'

The views/blog/all.erb
< %# This section adds control on top  %>
< p>
< a href="/<%=$blogpath%>"> latest <%=$blogpath%>< /a>

<% if @offset>($blogs_per_page-1) %>
| < a href="/<%=$blogpath%>/older/<%=@offset-$blogs_per_page%>"> newer <%=$blogpath%>< /a>

| < a href="/<%=$blogpath%>/older/<%=@offset+$blogs_per_page%>"> older <%=$blogpath%>< /a>
< /p>

<%# This section lists all the Posts passed to it %>
<% for post in @posts %>
< h2>< a href="/<%=$blogpath%>/<>"> <%= post.title %>< /a>< /h2>
< p><%=post.body%>< /p>
<% end %>

No comments: