Class: LivingDocument::CodeEvaluator

Inherits:
Object
  • Object
show all
Includes:
MemoWise
Defined in:
lib/living_document/code_evaluator.rb

Instance Method Summary collapse

Constructor Details

#initialize(code:) ⇒ CodeEvaluator

Returns a new instance of CodeEvaluator.



6
7
8
9
10
11
12
13
# File 'lib/living_document/code_evaluator.rb', line 6

def initialize(code:)
  @code = code.gsub(/^=begin\b.*?^=end\n/m, '')

  @known_erroring_segment_indexes = []
  @random_seed = rand(1_000_000_000)

  $printed_output_last_run = ''
end

Instance Method Details

#evaluated_codeObject



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/living_document/code_evaluator.rb', line 15

def evaluated_code
  save_original_stdout

  Timecop.freeze do
    printed_code_segments.each_with_index do |printed_code_segment, index|
      $printed_output = ''
      set_up_capturing_stdout

      result =
        begin
          # We need to namespace any constants that would otherwise leak and persist globally.
          new_namespace.
            instance_eval(code_to_eval(index)).
            inspect.
            squish.
            then do |evaluated_result|
              if newly_printed_output.present?
                result_for_printed_output
              else
                formatted_evaluated_result(evaluated_result)
              end
            end
        rescue => error
          @known_erroring_segment_indexes << index

          "raises #{error.class} (#{error.message})"
        end

      remember_printed_output

      swap_in_evaluated_code(printed_code_segment, result)
    end
  end

  @code
ensure
  restore_original_stdout
end