Files
nairobi/app/models/legislation/draft_version.rb
Javi Martín 68ca29fa8b Convert markdown to HTML on demand
We were converting markdown to HTML every time we saved a record, which
has the same problems as sanitizing HTML before saving it to the
database, particularly because the body of a legislation draft is stored
in a translations table.

Performance-wise this isn't a problem: converting a text with more than
200_000 characters takes about a milisecond on my machine.

Note we need to modify a migration generated by globalize, since the
method `create_translation_table!` would fail now that we don't define
`translates :body_html` in the model.
2019-10-21 21:32:43 +02:00

41 lines
1.2 KiB
Ruby

class Legislation::DraftVersion < ApplicationRecord
VALID_STATUSES = %w[draft published]
acts_as_paranoid column: :hidden_at
include ActsAsParanoidAliases
translates :title, touch: true
translates :changelog, touch: true
translates :body, touch: true
include Globalizable
belongs_to :process, class_name: "Legislation::Process", foreign_key: "legislation_process_id"
has_many :annotations, class_name: "Legislation::Annotation", foreign_key: "legislation_draft_version_id", dependent: :destroy
validates_translation :title, presence: true
validates_translation :body, presence: true
validates :status, presence: true, inclusion: { in: VALID_STATUSES }
scope :published, -> { where(status: "published").order("id DESC") }
def body_html
renderer = Redcarpet::Render::HTML.new(with_toc_data: true)
Redcarpet::Markdown.new(renderer).render(body)
end
def toc_html
renderer = Redcarpet::Render::HTML_TOC.new(with_toc_data: true)
Redcarpet::Markdown.new(renderer).render(body)
end
def display_title
status == "draft" ? "#{title} *" : title
end
def total_comments
annotations.sum(:comments_count)
end
end