| Total Complexity | 6 |
| Total Lines | 36 |
| Duplicated Lines | 0 % |
| Changes | 2 | ||
| Bugs | 0 | Features | 1 |
| 1 | # frozen_string_literal: true |
||
| 4 | class Journal < ApplicationRecord |
||
| 5 | belongs_to :participant, inverse_of: :journal |
||
| 6 | has_many :journal_entries, inverse_of: :journal, dependent: :destroy |
||
| 7 | validates :participant, presence: true |
||
| 8 | validates :name, presence: true |
||
| 9 | validates_uniqueness_of :name |
||
| 10 | validates_length_of :name, \ |
||
| 11 | within: 2..50, \ |
||
| 12 | too_long: 'pick a shorter name', \ |
||
| 13 | too_short: 'pick a longer name' |
||
| 14 | |||
| 15 | after_initialize :create_entry_for_today |
||
| 16 | |||
| 17 | def list_entries(limit: 4) |
||
| 18 | entries = journal_entries.order('entry_date DESC').limit(limit) |
||
| 19 | entries.join(' ') |
||
| 20 | end |
||
| 21 | |||
| 22 | def read_entry(day) |
||
| 23 | JournalEntry.where(entry_date: day.beginning_of_day..day.end_of_day) |
||
| 24 | end |
||
| 25 | |||
| 26 | def read_last(last_n: 1) |
||
| 27 | JournalEntry.order('ID DESC').limit(last_n) |
||
| 28 | end |
||
| 29 | |||
| 30 | def to_s |
||
| 31 | name |
||
| 32 | end |
||
| 33 | |||
| 34 | private |
||
| 35 | |||
| 36 | def create_entry_for_today |
||
| 37 | journal_entries.concat(JournalEntry.new(journal: self)) if new_record? |
||
| 38 | end |
||
| 39 | end |
||
| 40 |