Last active
September 4, 2020 17:15
-
-
Save apauly/e732e2a63c3098d7585de26c181624cc to your computer and use it in GitHub Desktop.
ActionText: Use preloaded ActiveStorage attachments
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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