Class: FileReader

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

Overview

This class reads Persons and Tasks from a file specified by the provided filename. For a successful reading process the file need to fit the format specified in the FileWriter

Class Method Summary collapse

Class Method Details

.read_all_persons(input, repo) ⇒ Integer

method to read all persons from the file and store them in the DataRepository

Parameters:

Returns:

  • (Integer)

    the highest person id



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

def self.read_all_persons(input, repo)
  max_person_id = 0
  while (line = input.gets)
    break if (line =~ />/)
    type = line.split(" ")[0].split("::").inject(Object) {|o,c|
      o.const_get c
    }
    p = type.create_from_attribute_list(input.gets.chomp.split(";"))
    max_person_id = p.id if (p.id > max_person_id)
    repo.add_person(p)
    input.gets # removes closing } from a person
  end

  return max_person_id
end

.read_all_tasks(input, repo) ⇒ Integer

method to read all tasks from the file and store them in the DataRepository

Parameters:

Returns:

  • (Integer)

    the highest task id



57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/data/file_storage/file_reader.rb', line 57

def self.read_all_tasks(input, repo)
  max_task_id = 0
  while (line = input.gets)
    break if (line =~ />/)
    id = line.split(" ")[0].to_i

    t = Task::Task.create_from_attribute_list(input.gets.chomp.split(";"))
    max_task_id = t.id if (t.id > max_task_id)
    repo.add_task_to_person(id,t)
    input.gets # removes closing } from a task
  end

  return max_task_id
end

.read_file(filename) ⇒ Object

singleton method to read a file specified by filename

Parameters:

  • filename (String)

    the file name of the requested file



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/data/file_storage/file_reader.rb', line 13

def self.read_file(filename)
  input = File.open(filename, "r")
  repo = DataRepository.new()
  ids = Array.new()

  while(line = input.gets && !line =~ /Persons </); end
  ids << read_all_persons(input, repo)

  while(line = input.gets && !line =~ /Tasks </); end
  ids << read_all_tasks(input, repo)

  repo.set_max_ids(ids)

  return repo
end