3 # The context provides an abstraction layer between ohcount and the
6 # SimpleFileContext provides ohcount with the target filename and a means
7 # to access the contents of the file.
9 # In simple usage scenarios, the SimpleFileContext can simply point to an actual
10 # file on disk. In more complex scenarios, the context allows the
11 # file contents to be delivered to ohcount from a temp file or
14 class SimpleFileContext
15 # The original name of the file to be analyzed.
16 # This name will be used when detecting the language.
19 # An array of names of other files in the source tree which
20 # may be helpful when disambiguating the language used by the target file.
21 # For instance, the presence of an Objective-C *.m file is a clue when
22 # determining the language used in a *.h header file.
23 # This array is optional, but language identification may be less accurate
25 attr_reader :filenames
27 # The location on disk where the file content can currently be found.
28 # This might not be the same as the original name of the file.
29 # For example, file content might be stored in temporary directory.
30 attr_reader :file_location
32 # At a minimum, you must provide the filename.
34 # You may also optionally pass an array of names of other files in the source tree.
35 # This will assist when disambiguating the language used by the source file.
36 # If you do not include this array, language identification may be less accurate.
38 # The SimpleFileContext must provide access to the file content. You can do this
39 # by one of three means, which will be probed in the following order:
41 # 1. You may optionally pass the content of the source file as string +cached_contents+.
43 # 2. You may optionally provide +file_location+ as the name of a file on disk
44 # which contains the content of this source file.
46 # 3. If you do neither 1 nor 2, then +filename+ will be assumed to be an actual file on
47 # disk which can be read.
49 def initialize(filename, filenames = [], cached_contents = nil, file_location = nil)
51 @filenames = filenames
52 @cached_contents = cached_contents
53 @file_location = file_location || filename
56 # Returns the entire content of the target file as a single string.
58 return @cached_contents if @cached_contents
60 File.open(file_location) do |f|
61 @cached_contents = f.read
64 return @cached_contents