OSDN Git Service

[shogi-server]
[shogi-server/shogi-server.git] / shogi_server / league / persistent.rb
1 module ShogiServer
2
3 class League
4   #
5   # This manages those players who have their player_id.
6   # Since mk_rate mainly updates the yaml file, basically,
7   # this only reads data. But this writes some properties.
8   # TODO Such data should be facoted out to another file
9   #
10   class Persistent
11     def initialize(filename)
12       @db = YAML::Store.new(filename)
13       @db.transaction do |pstore|
14         @db['players'] ||= Hash.new
15       end
16     end
17
18     #
19     # trancaction=true means read only
20     #
21     def each_group(transaction=false)
22       @db.transaction(transaction) do
23         groups = @db["players"] || Hash.new
24         groups.each do |group, players|
25           yield group,players
26         end
27       end
28     end
29
30     def load_player(player)
31       return unless player.player_id
32
33       hash = nil
34       each_group(true) do |group, players|
35         hash = players[player.player_id]
36         break if hash
37       end
38       return unless hash
39
40       # a current user
41       player.name          = hash['name']
42       player.rate          = hash['rate'] || 0
43       player.modified_at   = hash['last_modified']
44       player.rating_group  = hash['rating_group']
45       player.win           = hash['win']  || 0
46       player.loss          = hash['loss'] || 0
47       player.last_game_win = hash['last_game_win'] || false
48     end
49
50     def save(player)
51       return unless player.player_id
52
53       each_group do |group, players|
54         hash = players[player.player_id]
55         if hash
56           # write only this property. 
57           # the others are updated by ./mk_rate
58           hash['last_game_win'] = player.last_game_win
59           break
60         end
61       end
62     end
63
64     def get_players
65       players = []
66       each_group(true) do |group, players_hash|
67         players << players_hash.keys
68       end
69       return players.flatten.collect do |player_id|
70         p = BasicPlayer.new
71         p.player_id = player_id
72         load_player(p)
73         p
74       end
75     end
76   end # class Persistent
77
78 end # class League
79 end # module ShogiServer