Class: Reading::Stats::Grouping

Inherits:
Object
  • Object
show all
Defined in:
lib/reading/stats/grouping.rb

Overview

The part of the query right after the operation, which groups the results, e.g. “by genre, rating”.

Class Method Summary collapse

Class Method Details

.group(input, items) ⇒ Hash

Determines which group(s) the input indicates, and then groups the Items accordingly. For the groups and their actions, see the constants below.

Parameters:

  • input (String)

    the query string.

  • items (Array<Item>)

    the Items on which to run the operation.

Returns:

  • (Hash)

    the return value of the group action(s).



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/reading/stats/grouping.rb', line 12

def self.group(input, items)
  grouped_items = {}

  match = input.match(REGEX)

  if match
    group_names = match[:groups]
      .split(',')
      .tap { _1.last.sub!(/(\w)\s+\w+/, '\1') }
      .map(&:strip)
      .map { _1.delete_suffix('s') }
      .map(&:to_sym)

    if group_names.uniq.count < group_names.count
      raise InputError, "Each grouping can be applied only once in a query."
    end

    begin
      return group_hash(items, group_names)
    rescue InputError => e
      raise e.class, "#{e.message} in \"#{input}\""
    end
  end

  { all: items }
end