# Add this file to `spec/support/rails_log_splitter.rb`

require "stringio"
require "logger"
require "fileutils"

class RailsLogSplitter
  def initialize(all: false)
    @io = StringIO.new
    @logger = Logger.new(@io)
    @all = all

    Rails.logger.extend(ActiveSupport::Logger.broadcast(@logger))
  end

  def run(example)
    clear
    append_heading_to_log(example)
    example.call
    save(log_path(example)) if save?(example)
  end

  private

  def clear
    @io.rewind
    @io.truncate(0)
  end

  def append_heading_to_log(example)
    width = example.full_description.length + 2
    heading = <<~HEADING
      \033[0;33m
      ##{"#" * width}
      #
      # #{example.full_description}
      # rspec #{example.location}
      #
      ##{"#" * width}
      \033[0m
    HEADING

    Rails.logger << heading
  end

  def save?(example)
    @all || example.exception.present?
  end

  def save(path)
    FileUtils.mkdir_p(File.dirname(path))
    File.write(path, @io.string)
  end

  def log_path(example)
    path = example.file_path
    path = File.expand_path(path, Rails.root.to_s)
    path = path.sub(%r{\A#{Regexp.escape(Rails.root.to_s)}/*}, "")
    path = path.sub(%r{\.rb\Z}, "")
    path << "_line_#{example.metadata[:line_number]}.log"
    Rails.root.join("log", Rails.env.to_s, path)
  end
end

RSpec.configure do |config|
  log_splitter = RailsLogSplitter.new
  
  config.around do |example|
    log_splitter.run(example)
  end
end