Module: ConcernsOnRails::Models::Sortable::ClassMethods

Includes:
Support::ColumnGuard
Defined in:
lib/concerns_on_rails/models/sortable.rb

Overview

class methods Example: Task.sortable_by(priority: :asc) A real module (not class_methods do) so the helpers aren't constrained by Metrics/BlockLength (the Stateable precedent).

Instance Method Summary collapse

Methods included from Support::ColumnGuard

#ensure_columns!, #ensure_columns_on!, #schema_reachable?

Instance Method Details

#sortable_by(field_config = nil, use_acts_as_list: true, scope: nil, add_new_at: nil, default_scope: true, **field_options) ⇒ Object

Define sortable field and direction. Example:

sortable_by :position
sortable_by position: :asc
sortable_by position: :desc

sortable_by :position, use_acts_as_list: false
sortable_by :position, scope: :list_id        # independent ordering within each list
sortable_by :position, add_new_at: :top       # new records go to the top of the list
sortable_by :position, default_scope: false   # no sticky ordering; chain .sorted


56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/concerns_on_rails/models/sortable.rb', line 56

def sortable_by(field_config = nil, use_acts_as_list: true, scope: nil, add_new_at: nil,
                default_scope: true, **field_options)
  field, direction = resolve_sortable_config(field_config, field_options)

  # set class attributes
  self.sortable_default_scope = default_scope ? true : false
  self.sortable_field = field
  self.sortable_direction = direction

  ensure_columns!("ConcernsOnRails::Models::Sortable", sortable_field)

  return unless use_acts_as_list

  # Thread acts_as_list's own options through (scope: for per-group ordering,
  # add_new_at: for where freshly-inserted rows land).
  list_options = { column: sortable_field }
  list_options[:scope] = scope unless scope.nil?
  list_options[:add_new_at] = add_new_at unless add_new_at.nil?
  acts_as_list(list_options)
end