module Lexorank::Rankable::ClassMethods

Attributes

ranking_column[R]
ranking_group_by[R]

Public Instance Methods

rank!(field: :rank, group_by: nil) click to toggle source
# File lib/lexorank/rankable.rb, line 10
def rank!(field: :rank, group_by: nil)
  @ranking_column = check_column(field)
  if group_by
    @ranking_group_by = check_column(group_by)
    unless @ranking_group_by
      warn "The supplied grouping by \"#{group_by}\" is neither a column nor an association of the model!"
    end
  end

  if @ranking_column
    self.scope :ranked, ->(direction: :asc) { where.not("#{field}": nil).order("#{field}": direction) }
    self.include Lexorank
    self.include InstanceMethods
  else
    warn "The supplied ranking column \"#{field}\" is not a column of the model!"
  end
end

Private Instance Methods

check_column(column_name) click to toggle source
# File lib/lexorank/rankable.rb, line 30
def check_column(column_name)
  return unless column_name
  # This requires an active connection... do we want this?
  if self.columns.map(&:name).include?(column_name.to_s)
    column_name
  # This requires rank! to be after the specific association
  elsif (association = self.reflect_on_association(column_name))
    association.foreign_key.to_sym
  end
end