Class: FileWriter

Inherits:
Object
  • Object
show all
Defined in:
lib/data/file_storage/file_writer.rb

Overview

This class stores the Persons and Tasks of a DataRepository into a file specified by #filename. The FileWriter stores the data in the following format:

Persons <
Person::Type {
parameter1;...;parameterN
}
Person::Type {
parameter1;...;parameterN
}
>
Tasks <
person_id {
parameter1;...;parameterN
}
person_id {
parameter1;...;parameterN
}
>

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(filename = "default_file") ⇒ FileWriter

initialization

Parameters:

  • filename (String) (defaults to: "default_file")

    the filename of the output file



30
31
32
# File 'lib/data/file_storage/file_writer.rb', line 30

def initialize(filename="default_file")
  @filename = filename
end

Instance Attribute Details

#filenameString (readonly)

Returns the filename of the output file.

Returns:

  • (String)

    the filename of the output file



26
27
28
# File 'lib/data/file_storage/file_writer.rb', line 26

def filename
  @filename
end

Instance Method Details

#write_all_persons(person_list) ⇒ Object

method to store a list of Persons in the file

Parameters:

  • person_list (Array)

    the list of persons



36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/data/file_storage/file_writer.rb', line 36

def write_all_persons(person_list)
  output = File.new(filename, "w")

  output.puts "Persons <"
  person_list.each { |person|
    output.puts "#{person.class} {"
    output.puts person.to_file
    output.puts "}"
  }
  output.puts ">"

  output.close
end

#write_all_tasks(repository) ⇒ Object

method to store a the Tasks in the file

Parameters:



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/data/file_storage/file_writer.rb', line 52

def write_all_tasks(repository)
  output = File.new(filename, "a")

  output.puts "Tasks <"
  repository.each_pair { |key, value|
    key_id = key.id
    value.each { |task|
      output.puts "#{key_id} {"
      output.puts task.to_file
      output.puts "}"
    }
  }
  output.print ">"

  output.close
end