Class: Alexandria::LibrarySortOrder

Inherits:
Object
  • Object
show all
Includes:
Logging
Defined in:
lib/alexandria/library_sort_order.rb

Direct Known Subclasses

Unsorted

Defined Under Namespace

Classes: Unsorted

Instance Method Summary collapse

Methods included from Logging

included, #log

Constructor Details

#initialize(book_attribute, ascending = true) ⇒ LibrarySortOrder

Returns a new instance of LibrarySortOrder.



11
12
13
14
# File 'lib/alexandria/library_sort_order.rb', line 11

def initialize(book_attribute, ascending = true)
  @book_attribute = book_attribute
  @ascending = ascending
end

Instance Method Details

#sort(library) ⇒ Object



16
17
18
19
20
21
22
23
24
25
# File 'lib/alexandria/library_sort_order.rb', line 16

def sort(library)
  sorted = library.sort_by do |book|
    book.send(@book_attribute)
  end
  sorted.reverse! unless @ascending
  sorted
rescue StandardError => ex
  log.warn { "Could not sort library by #{@book_attribute.inspect}: #{ex.message}" }
  library
end

#to_sObject



27
28
29
# File 'lib/alexandria/library_sort_order.rb', line 27

def to_s
  "#{@book_attribute} #{@ascending ? '(ascending)' : '(descending)'}"
end