Forum: Ruby on Rails [ANN] acts_as_ordered plugin

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Jonathan V. (Guest)
on 2006-03-30 11:26
(Received via mailing list)
Hey all,

I've just put together a little plugin to easily access the neighbours
of a
given model in a particular order. Read on if interested.

  script/plugin install

  class Person < ActiveRecord::Base
    acts_as_ordered :order => 'first_name'

Say you have people with first names of Adam, Jonathan and Robert:

  p = Person.find_by_first_name('Jonathan')              # Robert
  p.previous          # Adam
  p.previous.previous # Adam   (does not wrap around to end)         # Robert (does not wrap around to start)

If you want the next and previous methods to wrap around the ends, use:

  acts_as_ordered :order => 'first_name', :wrap => true

You can use this in a application to be able to quickly browse through
people. Eg:

  class PersonController < ApplicationController
    def view_neighbour
      # params[:direction] is passed off the page as 'next' or
      @person = Person.find(params[:id]).send(params[:direction])
      render :action => 'view'

Problems, comments, and suggestions all welcome.

Cheers, -Jonathan.
Jonathan V. (Guest)
on 2006-03-30 13:56
(Received via mailing list)
I've just added the ability to jump by more than one at a time.

Say you have people with first names of Adam, Jonathan and Robert:

  # Without wrapping (clamps to ends)
  p = Person.find_by_first_name('Jonathan')       # Robert     # Robert
  p.previous(100) # Jonathan

  # With wrapping (wraps around ends as many times as you like)
  p = Person.find_by_first_name('Jonathan')       # Adam
  p.previous(17)  # Robert

It will clamp or wrap around the ends depending on whether or not you
specify :wrap => true.

Cheers, -Jonathan.
eduard (Guest)
on 2006-03-30 23:40
(Received via mailing list)
Wow!  That's really cool.  Thanks,
This topic is locked and can not be replied to.