Files
nairobi/lib/ckeditor/backend/active_storage.rb
Javi Martín 8c82ff290b Handle CKEditor attachments with Active Storage
The code is based on what's generated using CKEditor's code generator.

We're doing one minor change to the `Ckeditor::Backend::ActiveStorage`
module; we're assigning the data in a `before_validation` instead of a
`before_save` callback. Validations with `file_validations` didn't work
otherwise; it looks like this backend was written with
`active_storage_validations` in mind [1].

Note we don't need to update the `name` column in the attachments table
because, when using Active Storage, CKEditor uses both `data` (as
attribute accessor) and `storage_data` (as attachment attribute).

[1] https://github.com/galetahub/ckeditor/blob/f9e48420ccb6dc/lib/generators/ckeditor/templates/active_record/active_storage/ckeditor/picture.rb#L4
2022-02-23 18:21:38 +01:00

74 lines
1.8 KiB
Ruby

# frozen_string_literal: true
# Code copied from the ckeditor gem:
# https://github.com/galetahub/ckeditor/pull/853
module Ckeditor
module Backend
module ActiveStorage
def self.included(base)
base.send(:include, Rails.application.routes.url_helpers)
base.send(:include, InstanceMethods)
base.send(:extend, ClassMethods)
end
module ClassMethods
def self.extended(base)
base.class_eval do
before_validation :apply_data
validate do
if data.nil? || file.nil?
errors.add(:data, :not_data_present, message: "data must be present")
end
end
end
end
end
module InstanceMethods
def url
rails_blob_path(self.storage_data, only_path: true)
end
def path
rails_blob_path(self.storage_data, only_path: true)
end
def styles
end
def content_type
self.storage_data.content_type
end
def content_type=(_content_type)
self.storage_data.content_type = _content_type
end
protected
def file
@file ||= storage_data
end
def blob
@blob ||= ::ActiveStorage::Blob.find(file.attachment.blob_id)
end
def apply_data
if data.is_a?(Ckeditor::Http::QqFile)
storage_data.attach(io: data, filename: data.original_filename)
else
storage_data.attach(data)
end
self.data_file_name = storage_data.blob.filename
self.data_content_type = storage_data.blob.content_type
self.data_file_size = storage_data.blob.byte_size
end
end
end
autoload :ActiveStorage, "ckeditor/backend/active_storage"
end
end