Skip to content

Instantly share code, notes, and snippets.

@apauly
Last active September 4, 2020 17:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apauly/e732e2a63c3098d7585de26c181624cc to your computer and use it in GitHub Desktop.
Save apauly/e732e2a63c3098d7585de26c181624cc to your computer and use it in GitHub Desktop.
ActionText: Use preloaded ActiveStorage attachments
Rails.application.config.after_initialize do
ActiveSupport.on_load(:action_text_content) do
class_eval do
attr_accessor :rich_text
def attachment_for_node(node, with_full_attributes: true)
attachment = ActionText::Attachment.from_node(node, rich_text&.find_preloaded_attachable(node))
with_full_attributes ? attachment.with_full_attributes : attachment
end
end
end
ActiveSupport.on_load(:action_text_rich_text) do
class_eval do
def body
super.tap{|body|
body.rich_text = self if body
}
end
def find_preloaded_attachable(node)
global_id = SignedGlobalID.parse(node['sgid'], for: ActionText::Attachable::LOCATOR_NAME)
return unless global_id.model_class == ActiveStorage::Blob && self.embeds.loaded?
self.embeds.detect{|embed|
embed.blob_id.to_s == global_id.model_id
}&.blob
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment