Module: Sequel::Plugins::Orderable::InstanceMethods

Defined in:
lib/sequel_orderable.rb

Instance Method Summary collapse

Instance Method Details

#at_position(p) ⇒ Object



23
24
25
26
27
28
29
30
# File 'lib/sequel_orderable.rb', line 23

def at_position(p)
  position_field = orderable_opts[:field]
  if scope_field = orderable_opts[:scope]
    dataset.first(scope_field => @values[scope_field], position_field => p)
  else
    dataset.first(position_field => p)
  end
end

#move_down(n = 1) ⇒ Object



71
72
73
74
# File 'lib/sequel_orderable.rb', line 71

def move_down(n = 1)
  # XXX: what if we're already at the bottom
  self.move_to(position+n)
end

#move_to(pos) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/sequel_orderable.rb', line 44

def move_to(pos)
  position_field = orderable_opts[:field]
  scope_field = orderable_opts[:scope]

  # XXX: error checking, negative pos?
  cur_pos = position
  return self if pos == cur_pos

  db.transaction do
    if pos < cur_pos
      ds = self.class.filter {position_field >= pos and position_field < cur_pos}
      ds.filter!(scope_field => @values[scope_field]) if scope_field
      ds.update(position_field => "#{position_field} + 1".lit)
    elsif pos > cur_pos
      ds = self.class.filter {position_field > cur_pos and position_field <= pos}
      ds.filter!(scope_field => @values[scope_field]) if scope_field
      ds.update(position_field => "#{position_field} - 1".lit)
    end
    set(position_field => pos)
  end
end

#move_to_bottomObject



80
81
82
83
84
85
86
87
# File 'lib/sequel_orderable.rb', line 80

def move_to_bottom
  position_field = orderable_opts[:field]
  scope_field = orderable_opts[:scope]
  ds = dataset
  ds = ds.filter(scope_field => @values[scope_field]) if scope_field
  last = ds.select(:max[position_field] => :max).first.values[:max].to_i
  self.move_to(last)
end

#move_to_topObject



76
77
78
# File 'lib/sequel_orderable.rb', line 76

def move_to_top
  self.move_to(1)
end

#move_up(n = 1) ⇒ Object



66
67
68
69
# File 'lib/sequel_orderable.rb', line 66

def move_up(n = 1)
  # XXX: position == 1 already?
  self.move_to(position-n)
end

#next(n = 1) ⇒ Object



39
40
41
42
# File 'lib/sequel_orderable.rb', line 39

def next(n = 1)
  target = position + n
  at_position(target)
end

#positionObject



19
20
21
# File 'lib/sequel_orderable.rb', line 19

def position
  @values[orderable_opts[:field]]
end

#prev(n = 1) ⇒ Object



32
33
34
35
36
37
# File 'lib/sequel_orderable.rb', line 32

def prev(n = 1)
  target = position - n
  # XXX: error checking, negative target?
  return self if position == target
  at_position(target)
end