123456789_123456789_123456789_123456789_123456789_

Class: Test::Unit::CodeSnippetFetcher

Relationships & Source Files
Inherits: Object
Defined in: lib/test/unit/code-snippet-fetcher.rb

Class Method Summary

Instance Method Summary

Constructor Details

.newCodeSnippetFetcher

[ GitHub ]

  
# File 'lib/test/unit/code-snippet-fetcher.rb', line 4

def initialize
  @sources = {}
end

Instance Method Details

#detect_encoding(first_line) (private)

[ GitHub ]

  
# File 'lib/test/unit/code-snippet-fetcher.rb', line 43

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

#fetch(path, line, options = {})

[ GitHub ]

  
# File 'lib/test/unit/code-snippet-fetcher.rb', line 8

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

#read_source(path) (private)

[ GitHub ]

  
# File 'lib/test/unit/code-snippet-fetcher.rb', line 26

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

#source(path)

[ GitHub ]

  
# File 'lib/test/unit/code-snippet-fetcher.rb', line 21

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