Module: ActsAsRestfulList::ClassMethods

Defined in:
lib/acts_as_restful_list.rb

Instance Method Summary collapse

Instance Method Details

#acts_as_restful_list(options = {}) ⇒ Object

acts_as_restful_list makes the class it is called on automatically behave like an ordered list. There are a number of options you can set:

  • column: The column to use as the position column. It’s set to position by default.

  • scope: The column to scope the list to. It takes a symbol with our without the _id.



13
14
15
16
17
18
19
20
21
22
23
24
25
26
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/acts_as_restful_list.rb', line 13

def acts_as_restful_list(options = {})
  include InstanceMethods
  
  configuration = {:column => :position}.merge(options)
  
  before_create :set_position
  after_update :reset_order_after_update
  after_destroy :reset_order_after_destroy
  
  define_method 'position_column' do
    configuration[:column].to_s
  end
  
  define_method 'scope_condition' do
    if configuration[:scope].nil?
      nil
    else
      scopes = Array(configuration[:scope]).collect do |scope|
        column = self.class.column_names.include?(scope.to_s) ? scope.to_s : "#{scope}_id"
        value = self.send(column)
        value.nil? ? "#{column} IS NULL" : "#{column} = #{value.is_a?(String) ? "'#{value}'" : value}"
      end
      scopes.join(' AND ')
    end
  end
  
  define_method 'scope_condition_was' do
    if configuration[:scope].nil?
      nil
    else
      scopes = Array(configuration[:scope]).collect do |scope|
        column = self.class.column_names.include?(scope.to_s) ? scope.to_s : "#{scope}_id"
        value = self.send("#{column}_was")
        value.nil? ? "#{column} IS NULL" : "#{column} = #{value.is_a?(String) ? "'#{value}'" : value}"
      end
      scopes.join(' AND ')
    end
  end
  
  define_method 'optimistic_locking_update' do
    self.class.column_names.include?("lock_version") ? ", lock_version = (lock_version + 1)" : ""
  end
end