Module: LexoRanker::RankableMethods::Adapters::ActiveRecord::ClassMethods

Defined in:
lib/lexoranker/rankable_methods/adapters/active_record.rb

Instance Method Summary collapse

Instance Method Details

#create_ranked(attributes, position: nil, &block) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/lexoranker/rankable_methods/adapters/active_record.rb', line 24

def create_ranked(attributes, position: nil, &block)
  position = case position
  when :top, :bottom
    [:"move_to_#{position}"]
  when Integer
    [:move_to, position]
  else
    [:"move_to_#{rankable_default_insert_pos}"]
  end
  instance = new(attributes, &block)
  instance.send(*position)
  instance.save
  instance
end

#ranks_around_position(id, position, scope_value: nil) ⇒ Object



39
40
41
42
43
# File 'lib/lexoranker/rankable_methods/adapters/active_record.rb', line 39

def ranks_around_position(id, position, scope_value: nil)
  scope = ranked.where.not(id: id)
  scope = scope.where("#{rankable_scope}": scope_value) unless scope_value.nil?
  scope.offset(position - 1).limit(2).pluck(:"#{rankable_column}")
end

#set_ranked_scope(field) ⇒ Object



12
13
14
# File 'lib/lexoranker/rankable_methods/adapters/active_record.rb', line 12

def set_ranked_scope(field)
  scope :ranked, ->(direction: :asc) { where.not("#{field}": nil).order("#{field}": direction) }
end

#set_ranked_validations(field, scope = nil) ⇒ Object



16
17
18
19
20
21
22
# File 'lib/lexoranker/rankable_methods/adapters/active_record.rb', line 16

def set_ranked_validations(field, scope = nil)
  if scope.nil?
    validates field, uniqueness: true, allow_nil: true
  else
    validates field, uniqueness: {scope: @rankable_scope}, allow_nil: true
  end
end