Class: RubyDocTest::Statement

Inherits:
Lines
  • Object
show all
Defined in:
lib/statement.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Lines

#inspect, #line_number, #lines, #range

Constructor Details

#initialize(doc_lines, line_index = 0, file_name = nil) ⇒ Statement

Tests

doctest: The FILENAME ruby constant should be replaced by the name of the file >> __FILE__

> “statement.rb”



24
25
26
27
# File 'lib/statement.rb', line 24

def initialize(doc_lines, line_index = 0, file_name = nil)
  @file_name = file_name
  super(doc_lines, line_index)
end

Instance Attribute Details

#actual_resultObject (readonly)

Returns the value of attribute actual_result.



17
18
19
# File 'lib/statement.rb', line 17

def actual_result
  @actual_result
end

Instance Method Details

#evaluateObject

Test

doctest: Evaluating a multi-line statement should be ok >> s = RubyDocTest::Statement.new([“>> b = 1 +”, “ 1”, “not part of the statement”]) >> s.evaluate

> 2

doctest: Evaluating a syntax error should raise an EvaluationError >> s = RubyDocTest::Statement.new([“>> b = 1 +”]) >> begin s.evaluate; :fail; rescue RubyDocTest::EvaluationError; :ok end

> :ok



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/statement.rb', line 63

def evaluate
  sc = source_code.gsub("__FILE__", @file_name.inspect)
  if RubyDocTest.verbose
    puts "EVAL: #{sc}"
  end
  @actual_result = eval(sc, TOPLEVEL_BINDING, __FILE__, __LINE__)
  if RubyDocTest.verbose
    puts "RESULT: #{@actual_result}"
  end
  @actual_result
rescue Exception => e
  if RubyDocTest.trace
    raise e.class, e.to_s + "\n" + e.backtrace.first
  else
    raise EvaluationError.new(self, e)
  end
end

#source_codeObject

Tests

doctest: A statement should parse out a ‘>>’ irb prompt >> s = RubyDocTest::Statement.new([“>> a = 1”]) >> s.source_code

> “a = 1”

doctest: More than one line should get included, if indentation so indicates >> s = RubyDocTest::Statement.new([“>> b = 1 +”, “ 1”, “not part of the statement”]) >> s.source_code

> “b = 1 +n1”

doctest: Lines indented by ?> should have the ?> removed. >> s = RubyDocTest::Statement.new([“>> b = 1 +”, “?> 1”]) >> s.source_code

> “b = 1 +n1”



45
46
47
48
49
50
# File 'lib/statement.rb', line 45

def source_code
  lines.first =~ /^#{Regexp.escape(indentation)}>>\s(.*)$/
  first = [$1]
  remaining = (lines[1..-1] || [])
  (first + remaining).join("\n")
end