Module: Codebreaker::Validation

Included in:
FileLoader, Game, User
Defined in:
lib/codebreaker/module/validation.rb

Defined Under Namespace

Classes: GameError, InvalidGuess, InvalidName, NoHintsLeft, NoSavedData, UnknownDifficulty

Constant Summary collapse

ERROR_MESSAGES =
{
  invalid_name: 'Name should be of 3 to 20 characters',
  invalid_guess: 'Expect 4 digits from 1 to 6',
  no_hints_left: 'No hints left, mate',
  no_difficulty: 'No such difficulty',
  no_save_data: 'No saved data is found'
}.freeze

Instance Method Summary collapse

Instance Method Details

#raise_error(error_class, error_message) ⇒ Object

Raises:

  • (error_class)


46
47
48
# File 'lib/codebreaker/module/validation.rb', line 46

def raise_error(error_class, error_message)
  raise error_class, ERROR_MESSAGES[error_message]
end

#validate_difficulty(difficulty, difficulties) ⇒ Object



29
30
31
# File 'lib/codebreaker/module/validation.rb', line 29

def validate_difficulty(difficulty, difficulties)
  raise_error(UnknownDifficulty, :no_difficulty) unless difficulties.keys.any?(difficulty.to_sym)
end

#validate_file_existens(file_path) ⇒ Object



42
43
44
# File 'lib/codebreaker/module/validation.rb', line 42

def validate_file_existens(file_path)
  raise_error(NoSavedData, :no_save_data) unless File.exist?(file_path)
end

#validate_guess(guess, length, range) ⇒ Object



33
34
35
36
# File 'lib/codebreaker/module/validation.rb', line 33

def validate_guess(guess, length, range)
  raise_error(InvalidGuess, :invalid_guess) unless guess.compact.length == length
  raise_error(InvalidGuess, :invalid_guess) if guess.compact.any? { |num| !range.cover? num }
end

#validate_hints(hints_used, hints_total) ⇒ Object



38
39
40
# File 'lib/codebreaker/module/validation.rb', line 38

def validate_hints(hints_used, hints_total)
  raise_error(NoHintsLeft, :no_hints_left) if hints_used >= hints_total
end

#validate_user_name(name, length) ⇒ Object



25
26
27
# File 'lib/codebreaker/module/validation.rb', line 25

def validate_user_name(name, length)
  raise_error(InvalidName, :invalid_name) unless length.cover?(name.length)
end