Class: Reading::Filter

Inherits:
Object show all
Defined in:
lib/reading/filter.rb

Overview

Filters Items based on given criteria.

Class Method Summary collapse

Class Method Details

.by(items:, no_sort: false, **criteria) ⇒ Array<Item>

Filters Items based on given criteria, and returns them sorted by last end date or (where there is none) status, where :planned Items are placed last, and :in_progress just before those.

Parameters:

  • items (Array<Item>)
  • no_sort (Boolean) (defaults to: false)

    to preserve the original ordering of the Items.

  • criteria (Hash)

    one or more of the filters defined in by_x methods below.

Returns:

Raises:

  • (ArgumentError)

    if criteria are invalid or missing.



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/reading/filter.rb', line 13

def by(items:, no_sort: false, **criteria)
  validate_criteria(**criteria)

  filtered = criteria.each.with_object(items.dup) { |(criterion, arg), filtered_items|
    send("#{CRITERIA_PREFIX}#{criterion}#{CRITERIA_SUFFIX}", filtered_items, arg)
  }

  return filtered if no_sort

  filtered.sort_by { |item|
    if item.done?
      item.last_end_date.strftime("%Y-%m-%d")
    else
      item.status.to_s
    end
  }
end