Class: GameCodebreaker::Memory
- Inherits:
-
Object
- Object
- GameCodebreaker::Memory
- Defined in:
- lib/game_codebreaker/memory.rb
Instance Attribute Summary collapse
-
#path ⇒ Object
Returns the value of attribute path.
-
#users ⇒ Object
Returns the value of attribute users.
Instance Method Summary collapse
- #add_games(object) ⇒ Object
- #exists?(object) ⇒ Boolean
- #get_user(object) ⇒ Object
- #info(user) ⇒ Object
-
#initialize(path) ⇒ Memory
constructor
A new instance of Memory.
- #load ⇒ Object
- #save(user) ⇒ Object
Constructor Details
#initialize(path) ⇒ Memory
Returns a new instance of Memory.
8 9 10 11 |
# File 'lib/game_codebreaker/memory.rb', line 8 def initialize( path ) @path = path File.exists?( path ) ? @users = load.users : @users = [] end |
Instance Attribute Details
#path ⇒ Object
Returns the value of attribute path.
6 7 8 |
# File 'lib/game_codebreaker/memory.rb', line 6 def path @path end |
#users ⇒ Object
Returns the value of attribute users.
6 7 8 |
# File 'lib/game_codebreaker/memory.rb', line 6 def users @users end |
Instance Method Details
#add_games(object) ⇒ Object
13 14 15 16 |
# File 'lib/game_codebreaker/memory.rb', line 13 def add_games( object ) @users.each { |user| @user = user if user.hash == object.hash } object.games.each { |game| @user.games << game } end |
#exists?(object) ⇒ Boolean
18 19 20 21 |
# File 'lib/game_codebreaker/memory.rb', line 18 def exists?( object ) @users.each { |user| return true if user.hash == object.hash } false end |
#get_user(object) ⇒ Object
23 24 25 26 |
# File 'lib/game_codebreaker/memory.rb', line 23 def get_user( object ) @users.each { |user| @user = user if user.hash == object.hash } @user end |
#info(user) ⇒ Object
28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/game_codebreaker/memory.rb', line 28 def info( user ) a = [] a << name = user.name a << surname = user.surname a << age = user.age a << total_game = user.games.size array_win = user.games.select { |game| game.win == true } a << total_win = array_win.size a << total_losses = ( user.games.select { |game| game.win == false } ).size average_turns = 0 and array_win.each { |game| average_turns += game.turns } total_win != 0 ? a << average_turns /= total_win : a << 0 average_level = 0 and user.games.select { |game| average_level += game.level } a << average_level /= total_game end |
#load ⇒ Object
48 49 50 |
# File 'lib/game_codebreaker/memory.rb', line 48 def load return Marshal.load File.open(@path,'r').read if File.exists?( @path ) end |
#save(user) ⇒ Object
43 44 45 46 |
# File 'lib/game_codebreaker/memory.rb', line 43 def save( user ) exists?( user ) ? ( add_games(user); user = get_user(user) ) : @users << user File.open(@path,'w') { |f| f.write Marshal.dump self } end |