Module: Sortifiable::ClassMethods

Defined in:
lib/sortifiable.rb

Instance Method Summary collapse

Instance Method Details

#acts_as_list(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. Given a symbol, it’ll attach _id (if it hasn’t already been added) and use that as the foreign key restriction. It’s also possible to give it an entire string that is interpolated if you need a tighter scope than just a foreign key. Example:

    acts_as_list :scope => 'user_id = #{user_id} AND completed = 0'
    

    It can also be given an array of symbols or a belongs_to association.



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/sortifiable.rb', line 48

def acts_as_list(options = {})
  options.reverse_merge!(:scope => [], :column => :position)

  if options[:scope].is_a?(Symbol)
    if reflections.key?(options[:scope])
      reflection = reflections[options.delete(:scope)]

      if reflection.belongs_to?
        options[:scope] = scope_from_association_reflection(reflection)
      else
        raise ArgumentError, "Only belongs_to associations can be used as a scope"
      end
    elsif options[:scope].to_s !~ /_id$/
      scope_name = "#{options[:scope]}_id"
      options[:scope] = scope_name.to_sym if column_names.include?(scope_name)
    end
  end

  options[:class] = self

  include InstanceMethods

  before_create  :add_to_list
  before_destroy :decrement_position_on_lower_items,             :if => :in_list?
  before_save    :decrement_position_on_lower_items_in_old_list, :if => :will_leave_list?
  before_save    :add_to_bottom_of_new_list,                     :if => :will_leave_list?

  self.acts_as_list_options = options
end