Sha256: 5ee1d8acccd44aa65f8bbe44d4e1e1165935cf091618cbe684ccc57269f713b4

Contents?: true

Size: 1.58 KB

Versions: 36

Compression:

Stored size: 1.58 KB

Contents

# frozen_string_literal: true

module CKEditor5::Rails::Hooks
  module Form
    class EditorInputBuilder
      def initialize(object_name, object, template)
        @object_name = object_name
        @object = object
        @template = template
      end

      def build_editor(method, options = {})
        html_options = build_html_options(method, options)
        add_validation_classes!(method, html_options)
        @template.ckeditor5_editor(**html_options)
      end

      private

      attr_reader :object_name, :object, :template

      def build_html_options(method, options)
        {
          name: build_field_name(method, options),
          initial_data: fetch_initial_data(method, options),
          id: options[:id] || "#{object_name}_#{method}".parameterize,
          **options
        }
      end

      def build_field_name(method, options)
        return options[:as] || method.to_s if object_name.blank?

        "#{object_name}[#{options[:as] || method}]"
      end

      def fetch_initial_data(method, options)
        return object.send(method) if object.respond_to?(method)

        options[:initial_data]
      end

      def add_validation_classes!(method, html_options)
        return unless object.respond_to?(:errors) && object.errors[method].present?

        html_options[:class] = [html_options[:class], 'is-invalid'].compact.join(' ')
      end
    end

    module FormBuilderExtension
      def ckeditor5(method, options = {})
        EditorInputBuilder.new(object_name, object, @template)
                          .build_editor(method, options)
      end
    end
  end
end

Version data entries

36 entries across 36 versions & 1 rubygems

Version Path
ckeditor5-1.19.5 lib/ckeditor5/rails/hooks/form.rb
ckeditor5-1.19.4 lib/ckeditor5/rails/hooks/form.rb
ckeditor5-1.19.3 lib/ckeditor5/rails/hooks/form.rb
ckeditor5-1.19.2 lib/ckeditor5/rails/hooks/form.rb
ckeditor5-1.19.1 lib/ckeditor5/rails/hooks/form.rb
ckeditor5-1.19.0 lib/ckeditor5/rails/hooks/form.rb
ckeditor5-1.18.3 lib/ckeditor5/rails/hooks/form.rb
ckeditor5-1.18.1 lib/ckeditor5/rails/hooks/form.rb
ckeditor5-1.18.0 lib/ckeditor5/rails/hooks/form.rb
ckeditor5-1.17.4 lib/ckeditor5/rails/hooks/form.rb
ckeditor5-1.17.3 lib/ckeditor5/rails/hooks/form.rb
ckeditor5-1.17.2 lib/ckeditor5/rails/hooks/form.rb
ckeditor5-1.17.1 lib/ckeditor5/rails/hooks/form.rb
ckeditor5-1.17.0 lib/ckeditor5/rails/hooks/form.rb
ckeditor5-1.16.2 lib/ckeditor5/rails/hooks/form.rb
ckeditor5-1.16.1 lib/ckeditor5/rails/hooks/form.rb
ckeditor5-1.16.0 lib/ckeditor5/rails/hooks/form.rb
ckeditor5-1.15.10 lib/ckeditor5/rails/hooks/form.rb
ckeditor5-1.15.9 lib/ckeditor5/rails/hooks/form.rb
ckeditor5-1.15.8 lib/ckeditor5/rails/hooks/form.rb