Module: ActiveRecord::Orderable::ClassMethods

Defined in:
lib/ar-orderable.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#orderable_columnObject

Returns the value of attribute orderable_column.



8
9
10
# File 'lib/ar-orderable.rb', line 8

def orderable_column
  @orderable_column
end

#orderable_scopeObject

Returns the value of attribute orderable_scope.



8
9
10
# File 'lib/ar-orderable.rb', line 8

def orderable_scope
  @orderable_scope
end

#skip_callbacks_for_orderableObject

Returns the value of attribute skip_callbacks_for_orderable.



8
9
10
# File 'lib/ar-orderable.rb', line 8

def skip_callbacks_for_orderable
  @skip_callbacks_for_orderable
end

Instance Method Details

#acts_as_orderable(options = {}) ⇒ Object

@:column [string] column name acts_as_orderable :column => “order_nr”



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/ar-orderable.rb', line 12

def acts_as_orderable options = {}
  return unless self.connection.table_exists?(self.table_name)
  self.orderable_column = (options[:column] || "order_nr").to_s
  self.skip_callbacks_for_orderable = options[:skip_callbacks]
  if self.columns_hash.keys.include? self.orderable_column
    self.orderable_scope  = options[:scope]
    self.before_save :pre_save_ordering
    self.before_destroy :pre_destroy_ordering
    self.default_scope { order(self.orderable_column) }
    #self.validates_uniqueness_of self.orderable_column, :scope => @orderable_scope
    include ActiveRecord::Orderable::InstanceMethods
  else
    msg = "[IMPORTANT] ActiveRecord::Orderable plugin: class #{self} has missing column '#{self.orderable_column}'"
    puts msg if Rails.env == "development"
    RAILS_DEFAULT_LOGGER.error msg
  end
end

#order_unorderedObject

updates all unordered items puts them into the end of list



31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/ar-orderable.rb', line 31

def order_unordered
  self.reset_column_information # because before this usual 'add_column' is executed and the new column isn't fetched yet
  self.group(self.orderable_scope).each do |obj|
    unordered_conditions = "#{self.orderable_column} IS NULL OR #{self.table_name}.#{self.orderable_column} = 0"
    ordered_conditions   = "#{self.orderable_column} IS NOT NULL AND #{self.table_name}.#{self.orderable_column} != 0"
    order_nr = obj.all_orderable.order(self.orderable_column).last[self.orderable_column] || 0
    obj.all_orderable.where(unordered_conditions).each do |item|
      order_nr += 1
      raw_orderable_update(item.id, order_nr)
    end
  end
end

#raw_orderable_update(id, nr) ⇒ Object



44
45
46
# File 'lib/ar-orderable.rb', line 44

def raw_orderable_update id, nr
  self.connection.execute("update #{self.table_name} set #{self.orderable_column} = #{nr.to_i} where #{self.table_name}.id = #{id.to_i};")
end