Class: Notes::Scanner

Inherits:
Object
  • Object
show all
Defined in:
lib/notes/scanner.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(tags = nil, &block) ⇒ Scanner

Create a new scanner

Examples:

scan = Notes::Scanner.new(["TODO", "@@@"]) do |note|
  puts "#{note.file} contains notes!"
end

class NotesCounter < Notes::Scanner
  attr_reader :notes

  def initialize tags = nil
    super(tags)
    @notes = []
    @callback = proc { |note| @notes << note }
  end
end


37
38
39
40
# File 'lib/notes/scanner.rb', line 37

def initialize tags = nil, &block
  @tags = tags || TAGS.dup
  @callback = block
end

Instance Attribute Details

#callbackObject

The block to execute when a note is found

Examples:

scanner.callback = proc { |note| puts note.file }

See Also:

  • :on_note


19
20
21
# File 'lib/notes/scanner.rb', line 19

def callback
  @callback
end

#tagsArray

The array of tags to look for

Examples:

scanner.tags << "FOO"

Returns:

  • (Array)

    the tags list



11
12
13
# File 'lib/notes/scanner.rb', line 11

def tags
  @tags
end

Instance Method Details

#on_note(&block) ⇒ Object

Define the callback to execute when a note is given

Examples:

scanner.on_note do |note|
  puts note.text
end

See Also:

  • :callback=


50
51
52
# File 'lib/notes/scanner.rb', line 50

def on_note &block
  @callback = block
end

#scan(source) ⇒ Object

Scan a source string

Examples:

scanner.scan("...//XXX urgent fix!")


58
59
60
61
62
63
64
65
66
# File 'lib/notes/scanner.rb', line 58

def scan source
  return if tags.empty? || callback.nil?
  rxp = regexp
  source.split("\n").each_with_index do |line, i|
    if rxp =~ line
      callback.call Note.new($1, line, i + 1)
    end
  end
end

#scan_file(path) ⇒ Object

Scan a file

Examples:

scanner.scan_file("foo.c")


72
73
74
75
76
77
78
79
80
81
82
# File 'lib/notes/scanner.rb', line 72

def scan_file path
  return if tags.empty? || callback.nil?
  rxp = regexp
  File.open(path, 'r') do |file|
    file.each_with_index do |line, i|
      if rxp =~ line
        callback.call Note.new($1, line, i + 1, path)
      end
    end
  end
end