Class: ActiveRecord::Arrangeable::ArrangeService

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

Constant Summary collapse

VALID_DIRECTIONS =
[:asc, :desc, :ASC, :DESC,
"asc", "desc", "ASC", "DESC"].freeze
DEFAULT_DIRECTION =
:asc

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(relation) ⇒ ArrangeService

Returns a new instance of ArrangeService.



13
14
15
# File 'lib/active_record_arrangeable/arrange_service.rb', line 13

def initialize(relation)
  @relation = is_a?(ActiveRecord::Relation) ? relation : relation.all
end

Class Method Details

.arrange(relation, *args) ⇒ Object



9
10
11
# File 'lib/active_record_arrangeable/arrange_service.rb', line 9

def self.arrange(relation, *args)
  self.new(relation).arrange!(args)
end

Instance Method Details

#arrange!(*args) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/active_record_arrangeable/arrange_service.rb', line 17

def arrange!(*args)
  preproces_args(args)

  args.each do |arg|
    if arg.is_a?(Hash)
      arg.each do |field, value|
        apply_arrange(field, value)
      end
    else
      apply_arrange(arg, DEFAULT_DIRECTION)
    end
  end

  @relation
end