Sha256: 2807c4b9837353af70cc9fc72bf527184792d3267e234fad397b93053e52bbc9

Contents?: true

Size: 1.47 KB

Versions: 14

Compression:

Stored size: 1.47 KB

Contents

module Test
  module Unit
    class CodeSnippetFetcher
      def initialize
        @sources = {}
      end

      def fetch(path, line, options={})
        n_context_line = options[:n_context_line] || 3
        lines = source(path)
        return [] if lines.nil?
        min_line = [line - n_context_line, 1].max
        max_line = [line + n_context_line, lines.length].min
        window = min_line..max_line
        window.collect do |n|
          attributes = {:target_line? => (n == line)}
          [n, lines[n - 1].chomp, attributes]
        end
      end

      def source(path)
        @sources[path] ||= read_source(path)
      end

      private
      def read_source(path)
        return nil unless File.exist?(path)
        lines = []
        File.open(path, "rb") do |file|
          first_line = file.gets
          break if first_line.nil?
          encoding = detect_encoding(first_line) || Encoding::UTF_8
          first_line.force_encoding(encoding)
          file.set_encoding(encoding)
          lines << first_line
          lines.concat(file.readlines)
        end
        lines
      end

      def detect_encoding(first_line)
        return nil unless first_line.respond_to?(:ascii_only?)
        return nil unless first_line.ascii_only?
        if /\b(?:en)?coding[:=]\s*([a-z\d_-]+)/i =~ first_line
          begin
            Encoding.find($1)
          rescue ArgumentError
            nil
          end
        else
          nil
        end
      end
    end
  end
end

Version data entries

14 entries across 14 versions & 3 rubygems

Version Path
win32-api-1.10.1 vendor/bundle/ruby/2.5.0/gems/test-unit-3.3.4/lib/test/unit/code-snippet-fetcher.rb
win32-api-1.10.0 vendor/bundle/ruby/2.5.0/gems/test-unit-3.3.4/lib/test/unit/code-snippet-fetcher.rb
win32-api-1.9.2 vendor/bundle/ruby/2.5.0/gems/test-unit-3.3.4/lib/test/unit/code-snippet-fetcher.rb
win32-api-1.9.1 vendor/bundle/ruby/2.5.0/gems/test-unit-3.3.4/lib/test/unit/code-snippet-fetcher.rb
tdiary-5.1.2 vendor/bundle/ruby/2.6.0/gems/test-unit-3.3.4/lib/test/unit/code-snippet-fetcher.rb
tdiary-5.1.1 vendor/bundle/ruby/2.6.0/gems/test-unit-3.3.4/lib/test/unit/code-snippet-fetcher.rb
tdiary-5.1.0 vendor/bundle/gems/test-unit-3.3.4/lib/test/unit/code-snippet-fetcher.rb
test-unit-3.3.4 lib/test/unit/code-snippet-fetcher.rb
test-unit-3.3.3 lib/test/unit/code-snippet-fetcher.rb
test-unit-3.3.2 lib/test/unit/code-snippet-fetcher.rb
tdiary-5.0.13 vendor/bundle/gems/test-unit-3.3.1/lib/test/unit/code-snippet-fetcher.rb
tdiary-5.0.12.1 vendor/bundle/gems/test-unit-3.3.1/lib/test/unit/code-snippet-fetcher.rb
test-unit-3.3.1 lib/test/unit/code-snippet-fetcher.rb
test-unit-3.3.0 lib/test/unit/code-snippet-fetcher.rb