class Character < ApplicationRecord belongs_to :user belongs_to :activity, optional: true has_many :character_items has_many :items, through: :character_items has_many :character_skills validates :name, presence: true validates_length_of :name, maximum: 15, message: "can't be longer than 15 characters" validates_uniqueness_of :name, message: "is already being used" validates_format_of :name, with: /\A[a-z]+\z/i, message: "must consist of letters only" after_create :create_skills def shift_item(gid, amount) CharacterItem.transaction do item = self.character_items.find_or_initialize_by(item: Item.find_by_gid(gid)) item.increment(:quantity, amount) item.save end end def skill_level(gid) self.character_skills.find_by(skill: Skill.find_by_gid(gid.to_s)).level end def activity_time_remaining return nil unless self.activity duration_data = self.activity.whatnot["duration"] duration = duration_data["base"] duration_data["scaling"].each do |skill, scaling_amount| duration -= self.skill_level(skill) * scaling_amount end duration = [duration, duration_data["minimum"]].max duration - (Time.now - self.activity_started_at) end private def create_skills Skill.all.each { |skill| self.character_skills.create(skill: skill, xp: 0) } end end