Class: GlobetrotterFile

Inherits:
Object
  • Object
show all
Defined in:
lib/globetrotter/file.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file) ⇒ GlobetrotterFile

Returns a new instance of GlobetrotterFile.



6
7
8
9
10
# File 'lib/globetrotter/file.rb', line 6

def initialize(file)
  @set = Set.new
  @file = open(file)
  parse
end

Instance Attribute Details

#setObject

Returns the value of attribute set.



12
13
14
# File 'lib/globetrotter/file.rb', line 12

def set
  @set
end

Instance Method Details

#open(file) ⇒ Object



14
15
16
17
18
19
20
21
# File 'lib/globetrotter/file.rb', line 14

def open(file)
  begin
    file = File.open(file, File::RDONLY|File::CREAT)
  rescue StandardError => e
    abort e.to_s
  end
  file
end

#parseObject

open



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/globetrotter/file.rb', line 23

def parse
  self.open if @file.nil?
  line_number = 0
  # parse line for IP
  @file.each_line do |line|
    line_number += 1
    begin
      ip = IPAddr.new(line.chomp)
      @set.add(ip)
    rescue StandardError => e
      abort "#{e} on line #{line_number}: '#{line}'"
    end
  end
  @file.close unless @file.nil?
  self
end

#to_sObject

write



50
51
52
# File 'lib/globetrotter/file.rb', line 50

def to_s
  @file.path
end

#writeObject

parse



40
41
42
43
44
45
46
47
48
# File 'lib/globetrotter/file.rb', line 40

def write
  begin
    File.open(@file, 'w') do |f|
      f.puts(@set.to_a.sort.join("\n"))
    end
  rescue StandardError => e
    abort e.to_s
  end
end