Class: Mastermind::TopTen

Inherits:
Object
  • Object
show all
Defined in:
lib/mastermind/top_ten.rb

Constant Summary collapse

FILE_NAME =
'topten.yaml'
MAXIMUM_TOP =
10

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(response: nil, file_name: FILE_NAME, storage: Datastore::YmlStore.instance) ⇒ TopTen

Returns a new instance of TopTen.



7
8
9
10
11
12
13
14
# File 'lib/mastermind/top_ten.rb', line 7

def initialize(response: nil, file_name: FILE_NAME, storage: Datastore::YmlStore.instance)
  @response = response || Message.new
  @file_name = file_name
  @datastore = storage

  @datastore.create_file_if_not_exist @file_name
  load_top_ten
end

Instance Attribute Details

#file_nameObject (readonly)

Returns the value of attribute file_name.



3
4
5
# File 'lib/mastermind/top_ten.rb', line 3

def file_name
  @file_name
end

#player_recordsObject (readonly)

Returns the value of attribute player_records.



3
4
5
# File 'lib/mastermind/top_ten.rb', line 3

def player_records
  @player_records
end

#responseObject (readonly)

Returns the value of attribute response.



3
4
5
# File 'lib/mastermind/top_ten.rb', line 3

def response
  @response
end

#top_ten_recordsObject (readonly)

Returns the value of attribute top_ten_records.



3
4
5
# File 'lib/mastermind/top_ten.rb', line 3

def top_ten_records
  @top_ten_records
end

Instance Method Details

#add_record(player) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/mastermind/top_ten.rb', line 22

def add_record(player)
  if player.is_a? Player
    player = player.to_h
  elsif player.is_a? Hash
    player
  else
    raise ArgumentError, 'Unsupported Player Value'
  end
  @top_ten_records << player
  arrange_top_ten
  save
end

#arrange_top_tenObject



35
36
37
38
39
40
# File 'lib/mastermind/top_ten.rb', line 35

def arrange_top_ten
  @top_ten_records.sort!{ |x, y|
      [x[:guesses], x[:time_taken]] <=> [y[:guesses], y[:time_taken]]
  }
  @top_ten_records = @top_ten_records.slice(0, MAXIMUM_TOP)
end

#fetch(number_or_hash) ⇒ Object



50
51
52
53
54
55
56
57
58
# File 'lib/mastermind/top_ten.rb', line 50

def fetch number_or_hash
  if number_or_hash.is_a? Hash
    record = number_or_hash
  elsif number_or_hash.is_a? Integer
    record = @top_ten_records[number_or_hash - 1]
  end
  player = Player.new(player: record)
  player
end

#fetch_allObject



42
43
44
45
46
47
48
# File 'lib/mastermind/top_ten.rb', line 42

def fetch_all
  @player_records = []
  @top_ten_records.each{ |val|
    @player_records << fetch(val)
  }
  @player_records
end

#load_top_tenObject



16
17
18
19
20
# File 'lib/mastermind/top_ten.rb', line 16

def load_top_ten
  @top_ten_records = @datastore.fetch_yml(@file_name) || []
  arrange_top_ten
  fetch_all
end

#saveObject



60
61
62
63
# File 'lib/mastermind/top_ten.rb', line 60

def save
  @datastore.save_top_ten @file_name, @top_ten_records
  load_top_ten
end