2018-10-08 17:44:25 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2018-04-13 19:23:04 -04:00
|
|
|
module ActionText
|
2018-02-08 15:48:45 -05:00
|
|
|
module Attribute
|
|
|
|
extend ActiveSupport::Concern
|
|
|
|
|
|
|
|
class_methods do
|
2018-06-07 08:39:09 -04:00
|
|
|
# Provides access to a dependent RichText model that holds the body and attachments for a single named rich text attribute.
|
|
|
|
# This dependent attribute is lazily instantiated and will be auto-saved when it's been changed. Example:
|
|
|
|
#
|
|
|
|
# class Message < ActiveRecord::Base
|
|
|
|
# has_rich_text :content
|
|
|
|
# end
|
|
|
|
#
|
|
|
|
# message = Message.create!(content: "<h1>Funny times!</h1>")
|
2019-12-04 22:12:26 -05:00
|
|
|
# message.content? #=> true
|
2018-06-07 08:39:09 -04:00
|
|
|
# message.content.to_s # => "<h1>Funny times!</h1>"
|
2018-10-04 08:00:38 -04:00
|
|
|
# message.content.to_plain_text # => "Funny times!"
|
2018-06-07 08:39:09 -04:00
|
|
|
#
|
|
|
|
# The dependent RichText model will also automatically process attachments links as sent via the Trix-powered editor.
|
|
|
|
# These attachments are associated with the RichText model using Active Storage.
|
|
|
|
#
|
|
|
|
# If you wish to preload the dependent RichText model, you can use the named scope:
|
|
|
|
#
|
|
|
|
# Message.all.with_rich_text_content # Avoids N+1 queries when you just want the body, not the attachments.
|
2018-10-06 10:51:39 -04:00
|
|
|
# Message.all.with_rich_text_content_and_embeds # Avoids N+1 queries when you just want the body and attachments.
|
2018-04-13 19:47:33 -04:00
|
|
|
def has_rich_text(name)
|
|
|
|
class_eval <<-CODE, __FILE__, __LINE__ + 1
|
|
|
|
def #{name}
|
2019-03-23 10:04:48 -04:00
|
|
|
rich_text_#{name} || build_rich_text_#{name}
|
2018-04-13 19:47:33 -04:00
|
|
|
end
|
2018-02-14 10:33:30 -05:00
|
|
|
|
2019-12-04 22:12:26 -05:00
|
|
|
def #{name}?
|
|
|
|
rich_text_#{name}.present?
|
|
|
|
end
|
|
|
|
|
2018-04-13 19:47:33 -04:00
|
|
|
def #{name}=(body)
|
2018-10-05 23:47:10 -04:00
|
|
|
self.#{name}.body = body
|
2018-04-13 19:47:33 -04:00
|
|
|
end
|
|
|
|
CODE
|
2018-02-14 10:33:30 -05:00
|
|
|
|
2019-03-17 17:22:46 -04:00
|
|
|
has_one :"rich_text_#{name}", -> { where(name: name) },
|
|
|
|
class_name: "ActionText::RichText", as: :record, inverse_of: :record, autosave: true, dependent: :destroy
|
2018-04-13 19:47:33 -04:00
|
|
|
|
|
|
|
scope :"with_rich_text_#{name}", -> { includes("rich_text_#{name}") }
|
2018-06-07 08:38:57 -04:00
|
|
|
scope :"with_rich_text_#{name}_and_embeds", -> { includes("rich_text_#{name}": { embeds_attachments: :blob }) }
|
2018-05-28 11:43:21 -04:00
|
|
|
end
|
2018-02-08 15:48:45 -05:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|