Last active
July 21, 2022 20:52
-
-
Save walterdavis/92345fe2ed32a66ae3115d433dec19cb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Post < ApplicaationRecord | |
attribute :warnings, array: true, default: Set.new | |
def has_warnings? | |
publishing_checklist.any? | |
end | |
private | |
def publishing_checklist | |
# return a list of warnings or an empty set | |
warnings.clear | |
warnings.add 'Slug should begin with the publish date as YYYY-MM-DD' unless dated_slug?) | |
warnings.add 'Slug should be formatted in kebab-case' unless kebab_slug? | |
warnings.add 'Comments are disabled' unless commentable? | |
warnings.add 'Missing an image' if default_picture? | |
warnings.add 'Body is missing' unless body? | |
warnings.add 'Keywords are missing' unless keywords? | |
warnings.add 'Publish date is not set' unless publish_on? | |
warnings | |
end | |
def dated_slug? | |
slug.to_s&.match?(%r[\A#{(publish_on || Date.today).to_date}-]) | |
end | |
def kebab_slug? | |
slug.to_s == slug.to_s.titleize.parameterize | |
end | |
def default_picture? | |
first_picture == Image::FALLBACK_IMAGE | |
end | |
end | |
class PostsController < ApplicationController | |
before_action :set_post, only: [:show, :edit, :update, :destroy] | |
before_action :show_warnings, only: %i[show edit] | |
... | |
private | |
def show_warnings | |
flash.now[:warning] = helpers.publish_warnings(@post) if @post.has_warnings? | |
end | |
end | |
module PublishHelper | |
def publish_warnings(record) | |
tag.div do | |
concat tag.h5 'Publish warnings:' | |
concat publish_warnings_summary(record) | |
end | |
end | |
def publish_warnings_summary(record) | |
tag.ul class: "rails-bootstrap-forms-error-summary" do | |
record.warnings.each do |error| | |
concat tag.li(error) | |
end | |
end | |
end | |
def publish_warnings_icon(record) | |
tag.i '', title: "#{record.warnings.join("\n")}", | |
class: 'fa fa-warning text-warning get-info' if record.has_warnings? | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment