Forum: Ruby on Rails [ANN] acts_as_ordered plugin

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community 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.

Install:
  script/plugin install
http://svn.viney.net.nz/things/rails/plugins/acts_as_ordered

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

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

  p = Person.find_by_first_name('Jonathan')

  p.next              # Robert
  p.previous          # Adam
  p.previous.previous # Adam   (does not wrap around to end)
  p.next.next         # 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
'previous'
      @person = Person.find(params[:id]).send(params[:direction])
      render :action => 'view'
    end
  end

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')
  p.next(2)       # Robert
  p.next(100)     # Robert
  p.previous(100) # Jonathan

  # With wrapping (wraps around ends as many times as you like)
  p = Person.find_by_first_name('Jonathan')
  p.next(8)       # 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.