aboutsummaryrefslogtreecommitdiffstats
path: root/actiontext/lib/action_text/attachments/trix_conversion.rb
blob: 24937d6c2276d7c39b96dc1332359fc52bfdd313 (plain) (blame)
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
26
27
28
29
30
31
32
33
34
# frozen_string_literal: true

module ActionText
  module Attachments
    module TrixConversion
      extend ActiveSupport::Concern

      class_methods do
        def fragment_by_converting_trix_attachments(content)
          Fragment.wrap(content).replace(TrixAttachment::SELECTOR) do |node|
            from_trix_attachment(TrixAttachment.new(node))
          end
        end

        def from_trix_attachment(trix_attachment)
          from_attributes(trix_attachment.attributes)
        end
      end

      def to_trix_attachment(content = trix_attachment_content)
        attributes = full_attributes.dup
        attributes["content"] = content if content
        TrixAttachment.from_attributes(attributes)
      end

      private
        def trix_attachment_content
          if partial_path = attachable.try(:to_trix_content_attachment_partial_path)
            ActionText::Content.renderer.render(partial: partial_path, object: self, as: model_name.element)
          end
        end
    end
  end
end