Class: Sortable::Sort

Inherits:
Object
  • Object
show all
Defined in:
lib/sortable.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(scope, column, direction, *args) ⇒ Sort

Returns a new instance of Sort.


34
35
36
37
38
39
# File 'lib/sortable.rb', line 34

def initialize(scope, column, direction, *args)
  @scope = scope
  @column = column
  @direction = direction
  @args = args
end

Instance Attribute Details

#argsObject (readonly)

Returns the value of attribute args.


32
33
34
# File 'lib/sortable.rb', line 32

def args
  @args
end

#scopeObject (readonly)

Returns the value of attribute scope.


32
33
34
# File 'lib/sortable.rb', line 32

def scope
  @scope
end

Instance Method Details

#allObject


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

def all
  all = scope.all

  if column
    all = all.merge(column.scope) if column.scope.present?

    if column.method
      all = all.public_send(column.method, direction.to_sym, *args)
    elsif column.column.is_a?(Symbol)
      all = all.order(column.column => direction)
    else
      all = all.order("#{column.column} #{direction}")
    end
  end

  all
end

#columnObject


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

def column
  columns[@column.to_s]&.first
end

#columnsObject


41
42
43
# File 'lib/sortable.rb', line 41

def columns
  @columns ||= create_columns
end

#create_column(column) ⇒ Object


78
79
80
81
82
83
84
# File 'lib/sortable.rb', line 78

def create_column(column)
  if column.respond_to?(:last) && column.last.is_a?(Hash)
    Column.new(*column[0...-1], **column.last)
  else
    Column.new(*column)
  end
end

#create_columnsObject


71
72
73
74
75
76
# File 'lib/sortable.rb', line 71

def create_columns
  scope.sortable.flat_map do |columns|
    columns = [columns] unless columns.all? { |column| column.is_a?(Symbol) }
    columns.map { |column| create_column(column) }
  end.group_by { |column| column.name.to_s }
end

#directionObject


63
64
65
# File 'lib/sortable.rb', line 63

def direction
  @direction.to_s == "desc" ? "desc" : "asc"
end