diff options
author | David Gay <david@davidgay.org> | 2021-05-02 22:38:32 -0400 |
---|---|---|
committer | David Gay <david@davidgay.org> | 2021-05-02 22:38:32 -0400 |
commit | 1b2de86007508ba86c6c9cb99fbdcac178045131 (patch) | |
tree | a007fc55acd2b54b5db108e3580928a9a006d71e /app/models | |
parent | 1d5083ddf7f2b285e63bb8019d38199e862fa1d8 (diff) |
Character items and inventory, with ability to add and remove items
Diffstat (limited to 'app/models')
-rw-r--r-- | app/models/character.rb | 10 | ||||
-rw-r--r-- | app/models/character_item.rb | 25 |
2 files changed, 35 insertions, 0 deletions
diff --git a/app/models/character.rb b/app/models/character.rb index 1c022ea..a158d88 100644 --- a/app/models/character.rb +++ b/app/models/character.rb @@ -1,5 +1,15 @@ class Character < ApplicationRecord belongs_to :user belongs_to :activity, optional: true + has_many :character_items + has_many :items, through: :character_items validates :name, presence: true + + 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 end diff --git a/app/models/character_item.rb b/app/models/character_item.rb new file mode 100644 index 0000000..b54f799 --- /dev/null +++ b/app/models/character_item.rb @@ -0,0 +1,25 @@ +class CharacterItem < ApplicationRecord + belongs_to :character + belongs_to :item + validates :quantity, presence: true + + after_initialize do + if self.new_record? + self.quantity ||= 0 + end + end + + after_save :destroy_if_zero_quantity + + scope :ordered_by_item_name, -> { includes(:item).order("items.name") } + + private + def destroy_if_zero_quantity + if self.quantity == 0 + destroy + elsif self.quantity < 0 + # TODO: Can improve this (at the least, with reporting, later). + raise ItemQuantityError + end + end +end |