Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

root/branches/2-1-caching/railties/lib/source_annotation_extractor.rb

Revision 7672, 1.4 kB (checked in by rick, 1 year ago)

Moved the SourceAnnotationExtractor to a separate file in case libraries try to load the rails rake tasks twice. rspec_on_rails, I'm looking at you. [Rick]

Line 
1 class SourceAnnotationExtractor
2   class Annotation < Struct.new(:line, :tag, :text)
3     def to_s(options={})
4       s = "[%3d] " % line
5       s << "[#{tag}] " if options[:tag]
6       s << text
7     end
8   end
9
10   def self.enumerate(tag, options={})
11     extractor = new(tag)
12     extractor.display(extractor.find, options)
13   end
14
15   attr_reader :tag
16
17   def initialize(tag)
18     @tag = tag
19   end
20
21   def find(dirs=%w(app lib test))
22     dirs.inject({}) { |h, dir| h.update(find_in(dir)) }
23   end
24
25   def find_in(dir)
26     results = {}
27
28     Dir.glob("#{dir}/*") do |item|
29       next if File.basename(item)[0] == ?.
30
31       if File.directory?(item)
32         results.update(find_in(item))
33       elsif item =~ /\.(builder|(r(?:b|xml|js)))$/
34         results.update(extract_annotations_from(item, /#\s*(#{tag}):?\s*(.*)$/))
35       elsif item =~ /\.(rhtml|erb)$/
36         results.update(extract_annotations_from(item, /<%\s*#\s*(#{tag}):?\s*(.*?)\s*%>/))
37       end
38     end
39
40     results
41   end
42
43   def extract_annotations_from(file, pattern)
44     lineno = 0
45     result = File.readlines(file).inject([]) do |list, line|
46       lineno += 1
47       next list unless line =~ pattern
48       list << Annotation.new(lineno, $1, $2)
49     end
50     result.empty? ? {} : { file => result }
51   end
52
53   def display(results, options={})
54     results.keys.sort.each do |file|
55       puts "#{file}:"
56       results[file].each do |note|
57         puts "  * #{note.to_s(options)}"
58       end
59       puts
60     end
61   end
62 end
Note: See TracBrowser for help on using the browser.