Method: Fable::StoryState#clean_output_whitespace

Defined in:
lib/fable/story_state.rb

#clean_output_whitespace(string) ⇒ Object

Cleans inline whitespace in the following way:

  • Removes all whitespace from the start/end of line (including just before an n)

  • Turns all consecutive tabs & space runs into single spaces (HTML-style)



404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
# File 'lib/fable/story_state.rb', line 404

def clean_output_whitespace(string)
  x = ""

  current_whitespace_start = -1
  start_of_line = 0

  string.each_char.with_index do |character, i|
    is_inline_whitespace = (character == " " || character == "\t")

    if is_inline_whitespace && current_whitespace_start == -1
      current_whitespace_start = i
    end

    if !is_inline_whitespace
      if(character != "\n" && (current_whitespace_start > 0) && current_whitespace_start != start_of_line)
        x += " "
      end

      current_whitespace_start = -1
    end

    if character == "\n"
      start_of_line = i + 1
    end

    if !is_inline_whitespace
      x << character
    end
  end

  return x

  # x = string.each_line(chomp: true).map do |line|
  #   if line.empty?
  #     nil
  #   else
  #     line.strip.gsub(MULTIPLE_WHITESPACE_REGEX, ' ') + "\n"
  #   end
  # end
  # cleaned_string = x.compact.join("\n")

  # cleaned_string
end