Class: FileDatabase
- Inherits:
-
Object
- Object
- FileDatabase
- Defined in:
- lib/keeperchallenge/database.rb
Instance Attribute Summary collapse
-
#folder_path ⇒ Object
readonly
Returns the value of attribute folder_path.
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 11 |
# File 'lib/keeperchallenge/database.rb', line 4 def initialize #if db folder does not exist, create it @folder_path = File.dirname(__FILE__) + "/db/" puts @folder_path unless File.directory?(@folder_path) Dir.mkdir(@folder_path) end end |
Instance Attribute Details
#folder_path ⇒ Object (readonly)
Returns the value of attribute folder_path.
2 3 4 |
# File 'lib/keeperchallenge/database.rb', line 2 def folder_path @folder_path end |
Instance Method Details
#clear ⇒ Object
Will remove all player files from the db directory
52 53 54 55 56 57 58 |
# File 'lib/keeperchallenge/database.rb', line 52 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
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/keeperchallenge/database.rb', line 15 def load(players) # read all files in database Dir.foreach(@folder_path) do |file| if !(file =='.' || file == '..') # create an object per file (=player) players.update({file => Player.new(file)}) # populate with activities content = File.open("#{@folder_path}#{file}") content.each_line do |line| activity = line.split(' ') players[file].add_activity(activity[0], activity[1], activity[2], activity[3]) end content.close end end end |
#save(players) ⇒ Object
will save player to static files in db directory
36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/keeperchallenge/database.rb', line 36 def save(players) # create a file per player players.each do |key,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 |