# frozen_string_literal: true # :markup: markdown require "active_support/core_ext/object/try" module ActionText # # Action Text Attachment # # Attachments serialize attachables to HTML or plain text. # # class Person < ApplicationRecord # include ActionText::Attachable # end # # attachable = Person.create! name: "Javan" # attachment = ActionText::Attachment.from_attachable(attachable) # attachment.to_html # => " "[racecar.jpg]" # # Use the `caption` when set: # # attachment = ActionText::Attachment.from_attachable(attachable, caption: "Vroom vroom") # attachment.to_plain_text # => "[Vroom vroom]" # # The presentation can be overridden by implementing the # `attachable_plain_text_representation` method: # # class Person < ApplicationRecord # include ActionText::Attachable # # def attachable_plain_text_representation # "[#{name}]" # end # end # # attachable = Person.create! name: "Javan" # attachment = ActionText::Attachment.from_attachable(attachable) # attachment.to_plain_text # => "[Javan]" def to_plain_text if respond_to?(:attachable_plain_text_representation) attachable_plain_text_representation(caption) else caption.to_s end end # Converts the attachment to HTML. # # attachable = Person.create! name: "Javan" # attachment = ActionText::Attachment.from_attachable(attachable) # attachment.to_html # => "" end private def node_attributes @node_attributes ||= ATTRIBUTES.to_h { |name| [ name.underscore, node[name] ] }.compact end def attachable_attributes @attachable_attributes ||= (attachable.try(:to_rich_text_attributes) || {}).stringify_keys end def sgid_attributes @sgid_attributes ||= node_attributes.slice("sgid").presence || attachable_attributes.slice("sgid") end end end