Module: Positionable::ClassMethods

Defined in:
lib/positionable.rb

Overview

This acts_as extension provides the capabilities for sorting and reordering a number of objects in a list. The class that has this specified needs to have a column defined as an integer on the mapped database table to store the list’s position. The default is position.

Todo list example:

class TodoList < ActiveRecord::Base
  has_many :todo_items, :order => "position"
end

class TodoItem < ActiveRecord::Base
  belongs_to :todo_list
  acts_as_positionable :scope => :todo_list_id
end

todo_list.first.move_to_bottom
todo_list.last.move_higher

Instance Method Summary collapse

Instance Method Details

#acts_as_positionable(options = {}) ⇒ Object

Configuration options are:

  • column - specifies the column name to use for keeping the position integer (default: position)

  • scope - restricts what is to be considered a list. Expects a symbol representing a object attribute

  • conditions - activerecord find conditions to evaluate if the record should be inserted on the list

  • list_name - the name for this list’s act_as_positionable declaration (default: :default)



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/positionable.rb', line 27

def acts_as_positionable(options = {})
  options = { :list_name => :default, :column => "position" }.merge(options)
  
  cattr_accessor :positionable unless respond_to?(:positionable)
  self.positionable ||= Positionable::Wrapper.new
  self.positionable << options
  
  named_scope :ascending, lambda { |*list_name|
    { :order => self.positionable.lists[list_name.first || :default][:column] }
  }
  named_scope :descending, lambda { |*list_name|
    { :order => "#{self.positionable.lists[list_name.first || :default][:column]} DESC" }
  }
  named_scope :conditions, lambda { |*list_name|
    { :conditions => self.positionable.lists[list_name.first || :default][:conditions] }
  }

  class_eval <<-EOV
    include Positionable::InstanceMethods
    
    def acts_as_positionable_class
      ::#{self.name}
    end
    
    before_create  :add_to_lists
    before_update  :update_lists
    before_destroy :remove_from_lists
  EOV
end