Module: SumsUp::Core::Parser

Defined in:
lib/sums_up/core/parser.rb

Overview

Validates and normalizes arguments passed to SumsUp.define.

Constant Summary collapse

LOWER_SNAKE_CASE_REGEXP =
/\A[[:lower:]]+(_[[:lower:]]+)*\z/

Class Method Summary collapse

Class Method Details

.parse_variant_specs!(no_arg_variants, arg_variants) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/sums_up/core/parser.rb', line 11

def parse_variant_specs!(no_arg_variants, arg_variants)
  variant_names = no_arg_variants + arg_variants.keys

  validate_unique!(variant_names)
  variant_names.each(&method(:validate_name_format!))
  arg_variants.each_value(&method(:validate_variant_args!))

  no_arg_variants
    .map { |variant| [variant, []] }
    .to_h
    .merge(arg_variants.map { |key, ary| [key, [*ary]] }.to_h)
end

.validate_name_format!(variant_name) ⇒ Object

Raises:



38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/sums_up/core/parser.rb', line 38

def validate_name_format!(variant_name)
  unless variant_name.is_a?(Symbol)
    raise(VariantNameError, "Expected a Symbol, got: #{variant_name}")
  end

  return if LOWER_SNAKE_CASE_REGEXP.match(variant_name.to_s)

  raise(
    VariantNameError,
    "Name is not lower_snake_case: #{variant_name}"
  )
end

.validate_unique!(variant_names) ⇒ Object

Raises:



24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/sums_up/core/parser.rb', line 24

def validate_unique!(variant_names)
  duplicates = variant_names
    .group_by(&:itself)
    .select { |_, values| values.length > 1 }
    .keys

  return if duplicates.empty?

  raise(
    DuplicateNameError,
    "Duplicated names: #{duplicates.join(", ")}"
  )
end

.validate_variant_args!(variant_args) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/sums_up/core/parser.rb', line 51

def validate_variant_args!(variant_args)
  case variant_args
  when Symbol
    validate_name_format!(variant_args)
  when Array
    variant_args.each(&method(:validate_name_format!))

    validate_unique!(variant_args)
  else
    raise(
      VariantArgsError,
      "Expected a Symbol or Array, got: #{variant_args}"
    )
  end
end