File: topic.rb

package info (click to toggle)
ruby-activerecord-import 1.4.1-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 840 kB
  • sloc: ruby: 4,698; makefile: 7
file content (25 lines) | stat: -rw-r--r-- 839 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# frozen_string_literal: true

class Topic < ActiveRecord::Base
  validates_presence_of :author_name
  validates :title, numericality: { only_integer: true }, on: :context_test
  validates :title, uniqueness: true
  validates :content, uniqueness: true
  validates :word_count, numericality: { greater_than: 0 }, if: :content?

  validate -> { errors.add(:title, :validate_failed) if title == 'validate_failed' }
  before_validation -> { errors.add(:title, :invalid) if title == 'invalid' }

  has_many :books, inverse_of: :topic
  belongs_to :parent, class_name: "Topic"

  composed_of :description, mapping: [%w(title title), %w(author_name author_name)], allow_nil: true, class_name: "TopicDescription"

  default_scope { where(approved: true) }

  private

  def word_count
    @word_count ||= content.to_s.scan(/\w+/).count
  end
end