класс Rails::SourceAnnotationExtractor
Реализует логику, стоящую за Rails::Command::NotesCommand. См. rails notes --help для информации об использовании.
Annotation объекты представляют собой тройки :line, :tag, :text, которые представляют строку, где находится аннотация, ее тег и текст. Обратите внимание, что имя файла не сохраняется.
Аннотации ищутся в комментариях и модулях с отступами, они должны начинаться с тега, за которым необязательно следует двоеточие. Все до конца строки (или закрывающего ERB тега комментария) считается текстом.
Атрибуты
Открытые методы класса
# File railties/lib/rails/source_annotation_extractor.rb, line 128
def self.enumerate(tag = nil, options = {})
tag ||= Annotation.tags.join("|")
extractor = new(tag)
dirs = options.delete(:dirs) || Annotation.directories
extractor.display(extractor.find(dirs), options)
end Выводит все аннотации с тегом tag в корневых директориях app, config, db, lib, и test (рекурсивно).
Если tag равно nil, выводятся аннотации с тегами по умолчанию или зарегистрированными тегами.
Конкретные директории можно явно указать, используя ключ :dirs в options.
Rails::SourceAnnotationExtractor.enumerate 'TODO|FIXME', dirs: %w(app lib), tag: true
Если у options есть флаг :tag, он будет передан каждому методу to_s аннотации.
См. SourceAnnotationExtractor#find_in для списка расширений файлов, которые будут учитываться.
Этот метод класса является единственной точкой входа для команды rails notes.
# File railties/lib/rails/source_annotation_extractor.rb, line 137 def initialize(tag) @tag = tag end
Открытые методы экземпляра
# File railties/lib/rails/source_annotation_extractor.rb, line 186
def display(results, options = {})
options[:indent] = results.flat_map { |f, a| a.map(&:line) }.max.to_s.size
results.keys.sort.each do |file|
puts "#{file}:"
results[file].each do |note|
puts " * #{note.to_s(options)}"
end
puts
end
end Выводит отображение имен файлов к аннотациям в results в порядке, определённом именем файла. Хэш options передается методу to_s каждой аннотации.
# File railties/lib/rails/source_annotation_extractor.rb, line 143
def find(dirs)
dirs.inject({}) { |h, dir| h.update(find_in(dir)) }
end Возвращает хэш, сопоставляющий имена файлов в dirs (рекурсивно) с массивами их аннотаций.
# File railties/lib/rails/source_annotation_extractor.rb, line 151
def find_in(dir)
results = {}
Dir.glob("#{dir}/*") do |item|
next if File.basename(item).start_with?(".")
if File.directory?(item)
results.update(find_in(item))
else
extension = Annotation.extensions.detect do |regexp, _block|
regexp.match(item)
end
if extension
pattern = extension.last.call(tag)
# In case a user-defined pattern returns nothing for the given set
# of tags, we exit early.
next unless pattern
# If a user-defined pattern returns a regular expression, we will
# wrap it in a PatternExtractor to keep the same API.
pattern = PatternExtractor.new(pattern) if pattern.is_a?(Regexp)
annotations = pattern.annotations(item)
results.update(item => annotations) if annotations.any?
end
end
end
results
end Возвращает хэш, сопоставляющий имена файлов в dir (рекурсивно) с массивами их аннотаций. Учитываются файлы с расширениями, зарегистрированными в Rails::SourceAnnotationExtractor::Annotation.extensions. Включаются только файлы с аннотациями.
© 2004–2021 David Heinemeier Hansson
Licensed under the MIT License.