validate game startable

This commit is contained in:
Jesse C. Fisher 2015-01-25 04:32:00 -08:00
parent 0c621d8f89
commit 52ab57fc51
2 changed files with 7 additions and 7 deletions

View File

@ -1,31 +1,31 @@
# The game class # The game class
class Game < ActiveRecord::Base class Game < ActiveRecord::Base
has_many :players, :dependent => :destroy has_many :players, dependent: :destroy
has_many :users, through: :players has_many :users, through: :players
accepts_nested_attributes_for :players accepts_nested_attributes_for :players
validates :title, presence: true validates :title, presence: true
def start def start
# Save the game to the database # Save the game to the database
return false unless startable?
save save
# Start the game TODO # Start the game TODO
end end
def validate_startable def validate_startable
@player_count = players.size @player_count = players.count
errors[:notice] = 'Must be at least 2 players.' if @player_count < 2 errors[:notice] = 'Must be at least 2 players.' if @player_count < 2
errors[:players] = 'Must be less than 5 players.' if @player_count > 4 errors[:players] = 'Must be less than 5 players.' if @player_count > 4
end end
def is_startable? def startable?
@player_count = players.size @player_count = players.size
@player_count.between?(2, 4) @player_count.between?(2, 4)
end end
def add_player_from_user(user) def add_player_from_user(user)
if can_accomodate(user) return false unless can_accomodate(user)
Player.create(user: user, game: self) self.players.create(user: user)
end
end end
def can_accomodate(user) def can_accomodate(user)

View File

@ -42,6 +42,6 @@ RSpec.describe Game, type: :model do
end end
it 'Can not be started if game is invalid' do it 'Can not be started if game is invalid' do
expect(@game.start).to eq false expect(@game.start).to raise_error
end end
end end