Module: Byebug::Helpers::ParseHelper

Overview

Utilities to assist command parsing

Instance Method Summary collapse

Instance Method Details

#get_int(str, cmd, min = nil, max = nil) ⇒ Object

Parses str of command cmd as an integer between min and max.

If either min or max is nil, that value has no bound.

TODO: Remove the ‘cmd` parameter. It has nothing to do with the methods purpose.



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/byebug/helpers/parse.rb', line 15

def get_int(str, cmd, min = nil, max = nil)
  if str !~ /\A-?[0-9]+\z/
    err = pr('parse.errors.int.not_number', cmd: cmd, str: str)
    return nil, errmsg(err)
  end

  int = str.to_i
  if min && int < min
    err = pr('parse.errors.int.too_low', cmd: cmd, str: str, min: min)
    return min, errmsg(err)
  elsif max && int > max
    err = pr('parse.errors.int.too_high', cmd: cmd, str: str, max: max)
    return max, errmsg(err)
  end

  int
end

#parse_steps(str, cmd) ⇒ Object

Returns str as an integer or 1 if str is empty.

Returns:

  • str as an integer or 1 if str is empty.



64
65
66
67
68
69
70
71
# File 'lib/byebug/helpers/parse.rb', line 64

def parse_steps(str, cmd)
  return 1 unless str

  steps, err = get_int(str, cmd, 1)
  return nil, err unless steps

  steps
end

#syntax_valid?(code) ⇒ Boolean

Returns true if code is syntactically correct for Ruby, false otherwise.

Returns:

  • (Boolean)

    true if code is syntactically correct for Ruby, false otherwise



36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/byebug/helpers/parse.rb', line 36

def syntax_valid?(code)
  return true unless code

  without_stderr do
    begin
      RubyVM::InstructionSequence.compile(code)
      true
    rescue SyntaxError
      false
    end
  end
end

#without_stderrObject

Temporarily disable output to $stderr



52
53
54
55
56
57
58
59
# File 'lib/byebug/helpers/parse.rb', line 52

def without_stderr
  stderr = $stderr
  $stderr.reopen(IO::NULL)

  yield
ensure
  $stderr.reopen(stderr)
end