class MonsterSpawn < ApplicationRecord belongs_to :monster belongs_to :location has_many :monster_spawn_combats after_initialize :set_starting_hp after_create :send_chat_message validates :starting_hp, presence: true, numericality: { greater_than_or_equal_to: 1, only_integer: true } def alive? self.remaining_hp > 0 end def remaining_hp self.starting_hp - MonsterSpawnCombat.where(monster_spawn: self).sum(:hp_lost) end private def set_starting_hp self.starting_hp = monster.max_hp end def send_chat_message chat_message = ChatMessage.new(body: "A leviathan has appeared in #{location.name}!", chat_room: ChatRoom.find_by_gid("news")) if chat_message.save ChatRoomChannel.broadcast_chat_message(chat_message) end end end