1
1
# frozen_string_literal: true
2
2
3
3
module ActionText
4
+ # = Action Text \Content
5
+ #
6
+ # The <tt>ActionText::Content</tt> class wraps an HTML fragment to add support for
7
+ # parsing, rendering and serialization. It can be used to extract links and
8
+ # attachments, convert the fragment to plain text, or serialize the fragment
9
+ # to the database.
10
+ #
11
+ # The <tt>ActionText::RichText</tt> record serializes the `body` attribute as
12
+ # <tt>ActionText::Content</tt>.
13
+ #
14
+ # class Message < ActiveRecord::Base
15
+ # has_rich_text :content
16
+ # end
17
+ #
18
+ # message = Message.create!(content: "<h1>Funny times!</h1>")
19
+ # body = message.content.body # => #<ActionText::Content "<div class=\"trix-conte...">
20
+ # body.to_s # => "<h1>Funny times!</h1>"
21
+ # body.to_plain_text # => "Funny times!"
4
22
class Content
5
23
include Rendering , Serialization
6
24
@@ -26,10 +44,21 @@ def initialize(content = nil, options = {})
26
44
end
27
45
end
28
46
47
+ # Extracts links from the HTML fragment:
48
+ #
49
+ # html = '<a href="http://example.com/">Example</a>'
50
+ # content = ActionText::Content.new(html)
51
+ # content.links # => ["http://example.com/"]
29
52
def links
30
53
@links ||= fragment . find_all ( "a[href]" ) . map { |a | a [ "href" ] } . uniq
31
54
end
32
55
56
+ # Extracts ActionText::Attachments from the HTML fragment:
57
+ #
58
+ # attachable = ActiveStorage::Blob.first
59
+ # html = %Q(<action-text-attachment sgid="#{attachable.attachable_sgid}" caption="Captioned"></action-text-attachment>)
60
+ # content = ActionText::Content.new(html)
61
+ # content.attachments # => [#<ActionText::Attachment attachable=#<ActiveStorage::Blob...
33
62
def attachments
34
63
@attachments ||= attachment_nodes . map do |node |
35
64
attachment_for_node ( node )
@@ -46,6 +75,12 @@ def gallery_attachments
46
75
@gallery_attachments ||= attachment_galleries . flat_map ( &:attachments )
47
76
end
48
77
78
+ # Extracts ActionText::Attachables from the HTML fragment:
79
+ #
80
+ # attachable = ActiveStorage::Blob.first
81
+ # html = %Q(<action-text-attachment sgid="#{attachable.attachable_sgid}" caption="Captioned"></action-text-attachment>)
82
+ # content = ActionText::Content.new(html)
83
+ # content.attachables # => [#<ActiveStorage::Blob...
49
84
def attachables
50
85
@attachables ||= attachment_nodes . map do |node |
51
86
ActionText ::Attachable . from_node ( node )
@@ -71,6 +106,10 @@ def render_attachment_galleries(&block)
71
106
self . class . new ( content , canonicalize : false )
72
107
end
73
108
109
+ # Returns the content as plain text with all HTML tags removed.
110
+ #
111
+ # content = ActionText::Content.new("<h1>Funny times!</h1>")
112
+ # content.to_plain_text # => "Funny times!"
74
113
def to_plain_text
75
114
render_attachments ( with_full_attributes : false , &:to_plain_text ) . fragment . to_plain_text
76
115
end
0 commit comments