Class: FileDatabase
- Inherits:
-
Object
- Object
- FileDatabase
- Defined in:
- lib/keeperchallenge/database.rb
Instance Method Summary collapse
-
#clear ⇒ Object
Will remove all player files from the db directory.
-
#initialize ⇒ FileDatabase
constructor
will create the db folder if not present on system.
-
#load(players) ⇒ Object
will load all files from db directory and load them as player and activities.
-
#save(players) ⇒ Object
will save player to static files in db directory.
Constructor Details
#initialize ⇒ FileDatabase
will create the db folder if not present on system
4 5 6 7 8 9 10 |
# File 'lib/keeperchallenge/database.rb', line 4 def initialize #if db folder does not exist, create it @folder_path = File.dirname(__FILE__) + "/db/" unless File.directory?(@folder_path) Dir.mkdir(@folder_path) end end |
Instance Method Details
#clear ⇒ Object
Will remove all player files from the db directory
51 52 53 54 55 56 57 |
# File 'lib/keeperchallenge/database.rb', line 51 def clear Dir.foreach(@folder_path) do |file| unless (file =='.' || file == '..') File.delete("#{@folder_path}#{file}") end end end |
#load(players) ⇒ Object
will load all files from db directory and load them as player and activities
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/keeperchallenge/database.rb', line 14 def load(players) index = 0 # read all files in database Dir.foreach(@folder_path) do |file| if !(file =='.' || file == '..') # create an object per file (=player) players.push(Player.new(file)) # populate with activities content = File.open("#{@folder_path}#{file}") content.each_line do |line| activity = line.split(' ') players[index].add_activity(activity[0], activity[1], activity[2], activity[3]) end index += 1 content.close end end end |
#save(players) ⇒ Object
will save player to static files in db directory
35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/keeperchallenge/database.rb', line 35 def save(players) # create a file per player players.each do |player| file_name = "#{@folder_path}#{player.name}" player_file = File.open(file_name,'w') # in this file : one activity per line, each attribute separated by a space player.activities.each do |activity| activity_string = "#{activity.type} #{activity.time} #{activity.cal} #{activity.km}\n" player_file.write(activity_string) end player_file.close end end |