Class: Sherlock::Collection::MatchedLine

Inherits:
String
  • Object
show all
Defined in:
lib/sherlock/collection/matched_line.rb

Overview

Attributes

  • :file

  • :line_number

  • :pattern

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(line, _attributes = {}) ⇒ MatchedLine

Returns a new instance of MatchedLine.



15
16
17
18
# File 'lib/sherlock/collection/matched_line.rb', line 15

def initialize(line, _attributes = {})
  super(line)
  self.attributes = {:original => line}.merge(_attributes)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m) ⇒ Object



37
38
39
40
41
42
43
# File 'lib/sherlock/collection/matched_line.rb', line 37

def method_missing(m)
  if attributes && value = attributes[m.to_s.intern]
    value
  else
    super
  end
end

Instance Attribute Details

#attributesObject

Returns the value of attribute attributes.



13
14
15
# File 'lib/sherlock/collection/matched_line.rb', line 13

def attributes
  @attributes
end

Instance Method Details

#changed?Boolean

Returns:

  • (Boolean)


20
21
22
# File 'lib/sherlock/collection/matched_line.rb', line 20

def changed?
  attributes[:original] != self
end

#gsub(*args, &block) ⇒ Object



24
25
26
# File 'lib/sherlock/collection/matched_line.rb', line 24

def gsub(*args, &block)
  self.class.new(super, attributes)
end

#match_dataObject



28
29
30
31
32
33
34
35
# File 'lib/sherlock/collection/matched_line.rb', line 28

def match_data
  attributes[:pattern].each do |p|
    if m = self.match(p)
      return m
    end
  end
  nil
end

#save!Object



45
46
47
48
49
50
51
52
53
54
# File 'lib/sherlock/collection/matched_line.rb', line 45

def save!
  all_lines = File.open(file, 'r') { |f| f.readlines }
  index = line_number - 1
  if original == all_lines[index]
    all_lines[index] = self.to_s
  else
    raise "File seems modified: #{file}"
  end
  File.open(file, 'w') {|f| f.write(all_lines) }
end