• Stars
    star
    31
  • Rank 820,005 (Top 17 %)
  • Language
    Ruby
  • License
    MIT License
  • Created almost 5 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Ruby on Rails + CKEditor 5

Rails + CKEditor 5

RailsJazz https://www.patreon.com/igorkasyanchuk Listed on OpenSource-Heroes.com

DEMO: https://new-ckeditor-demo.herokuapp.com/

Simple way to integrate Ruby on Rails application with CKEditor 5. This is the latest version of CKEditor which has more modern UI and cool toolbars. Main features:

  • Inline editor
  • Balloon editor
  • Classic editor
  • File uploads (custom controller & uploader)
  • Tables, Media, and other toolbar buttons
  • (requires maybe 10-15 minutes to configure gem, but works fine, better to clone and check source of demo)

Demo >> Demo site

Usage

1. Add gem
2. bundle
3. rails g new_ckeditor # to generate toolbars & configs
4. add js in application.js, or to the assets pipeline
5. in your form
  # to load CKEditor JS
  = javascript_include_tag 'new_ckeditor/classic/ckeditor', 'data-turbolinks-track': 'reload'
  
  # form control
  = f.ckeditor :description

Inline/Balloon

For inline/balloon editor you need to define a saver function, example is: app.js

  <p>
    <%= ckeditor_tag :content, @post.content, editor: { template: :balloon, type: :balloon, js: "sendData('#{update_inline_post_path(@post)}', editorHiddenField.value)" } %>
  </p>

Options:

  • teamplte - file with configuration for CKEditor, toolbar, path to upload files, etc
  • type - type of editor, depending on the type behavior is a little different. Balloon and inline editors works almost the same way. Classic works better as form field.

File uploads

Define logic for saving file (controller/uploader).

Sample: https://github.com/igorkasyanchuk/new_ckeditor_demo/blob/master/app/controllers/posts_controller.rb#L10-L23

You need also to configure your CKEditor editor config, sample: https://github.com/igorkasyanchuk/new_ckeditor_demo/blob/master/app/views/new_ckeditor/shared/_inline.html.erb#L50-L54

You need to define path to which send file and also CSRF token for security purposes. You can see how it works in example above.

Installation

Add this line to your application's Gemfile and run bundle:

gem 'new_ckeditor'

Configuration

File Upload with CKEditor 5

Gem doesn't have any strict dependency on any library. It's implemented this way on purpose to let developer use gem which he wants. Maybe in the future we can improve it.

But you can get a base skeleton where you can put your own logic.

Below I'll put an example of code which works with CKEditor.

  1. Let's start with new controller rails g controller file_uploads upload
class FileUploadsController < ApplicationController
  # note
  # that method must return json with URL to an uploaded image
  # or error message
  def upload
    image = CkEditorImage.new(file: params["upload"])
    if image.save
      render json: {
        url: image.file.url
      }
    else
      render json: {
        "error": {
          "message": image.errors.full_messages.join(", ")
        }
      }
    end
  end
end
  1. Create a new model where images will be stored: rails g model CkEditorImage file:string user_id:integer parent_id:integer parent_type:string
class CkEditorImage < ApplicationRecord
  mount_uploader :file, CkEditorImageUploader
  belongs_to :user, optional: true
  validates_presence_of :file
end

Code of migration may look like:

class CreateCkEditorImages < ActiveRecord::Migration[6.0]
  def change
    create_table :ck_editor_images do |t|
      t.string :file
      t.integer :user_id, index: true
      t.integer :parent_id
      t.string :parent_type

      t.datetime :created_at
      t.datetime :updated_at
    end
    add_index :ck_editor_images, :user_id
    add_index :ck_editor_images, [:parent_id, :parent_type]
  end
end

Run this migration.

  1. Create Carrierwave uploader rails g uploader CkEditorImage. Open and edit it if needed.

  2. Open again controller, edit logic, check user, check params, etc. You have a full control how to implement logic of storing files.

CKEditor 5 Toolbar Customization

You can edit in appropriate JS file, for example:

    toolbar: {
      items: [
        'heading',
        '|',
        'bold',
        'italic',
        'underline',
        'strikethrough',
        'link',
        'bulletedList',
        'numberedList',
        'alignment',
        '|',
        'indent',
        ...

You can create a copy of each classic, balloon', inline .js file and use. Or even creae custom build on ckeditor.com site and put in your app.

After that you can specify which exactly editor type and template with toolbar configuration to use:

<%= form.ckeditor :description, editor: { template: :inline, type: :inline } %>

Output

Output RAW HTML from CKEditor

To use same CSS as in editor, to keep consistent UI:

Require CSS file in application.css:

 *= require new_ckeditor/ckeditor.css

And in the view wrap output in .ck-content class:

<p>
  <strong>About:</strong>
  <div class="ck-content">
    <%= raw @user.about %>
  </div>
</p>

More documentation: https://ckeditor.com/docs/ckeditor5/latest/builds/guides/integration/content-styles.html

Styling

CKEditor 5 set min-height, height, width

.ck-editor__editable {
  min-height: 500px;
}

You can editor in some parent div and set height explicitly for editor inside.

TODO

  • configuration to specify toolbar
  • generators?
  • better and better readme
  • gif with demo
  • tests
  • check how it works with turbolinks?
  • fix issue fix JS map files
  • easier configuration
  • saver function to save inline/balloon editor

Customization

https://ckeditor.com/ckeditor-5/online-builder/

Contributing

Contribution directions go here.

License

The gem is available as open source under the terms of the MIT License.

More Repositories

1

rails_db

Rails Database Viewer and SQL Query Runner
JavaScript
1,447
star
2

active_storage_validations

Do it like => validates :photos, attached: true, content_type: ['image/png', 'image/jpg', 'image/jpeg'], size: { less_than: 500.kilobytes }, limit: { min: 1, max: 3 }, aspect_ratio: :landscape, dimension: { width: { in: 800..1600 }
Ruby
959
star
3

rails_performance

Monitor performance of you Rails applications (self-hosted and free)
Ruby
793
star
4

any_login

Easy way to login as any user in system
Ruby
376
star
5

log_analyzer

Rails logs analyzer (see how fast your views are rendering)
Ruby
349
star
6

rails_pdf

A reliable way to generate PDF of any complexity in Ruby on Rails apps
HTML
175
star
7

fake_api

The fastest way to prototype API in your Rails application
Ruby
142
star
8

execution_time

How fast is your code? See it directly in Rails console.
Ruby
111
star
9

benchmark_methods

Benchmark and measure execution time your Ruby methods without an additional code changes
Ruby
89
star
10

new_google_recaptcha

reCAPTCHA v3 Ruby on Rails gem
Ruby
82
star
11

transactify

Wrap your methods in DB Transactions
Ruby
55
star
12

sql_view

Rails SQL Views made easy ;)
Ruby
49
star
13

sweet_staging

Access your Rails console, see logs, execute rake commands directly from the browser. Great addition to your Staging ENV.
JavaScript
46
star
14

execute_sql

Execute SQL inside Rails console, or app itself
Ruby
41
star
15

cache_with_locale

Easy wait to do view caching with automatically added "locale" value to the cached key.
Ruby
37
star
16

avatarro

Generate google-style avatars in your application
Ruby
37
star
17

awesome_back_url

Redirect the user to the proper "back" page
Ruby
33
star
18

records_count

See in development logs how many records your queries returns. It can help with solving performance issues.
Ruby
31
star
19

amazon_static_site

Static website using https with your own domain name using Amazon S3 and Cloudflare for FREE
Ruby
29
star
20

omg_image

Generate PNG previews for HTML snippets (html/css/js). Any complexity.
Ruby
28
star
21

wrapped_print

Easy print debug information to your console in Ruby/Rails app.
Ruby
23
star
22

calculate_in_group

Group Active Record by ranges or set of values with a single SQL query.
Ruby
22
star
23

embed_view

Embed ERB files inside another ERB files for faster performance (5-20% BOOST!!!)
HTML
21
star
24

rails_time_travel

HTML
19
star
25

sabotage

Coding & debugging must be fun. Make life a bit harder for your colleagues :)
Ruby
18
star
26

mechanical

All models in a single table, new attributes without migrations. Works like regular AR model
Ruby
17
star
27

secrett11tto

Simple way to protect your content from copy-pasting
Ruby
15
star
28

rails_live

Ruby
15
star
29

mini-guard

Ruby
14
star
30

railsjazz.com

Rails Jazz (personal web site)
JavaScript
14
star
31

sidekiq_log_analyzer

SidekiqLogAnalyser gem allows to see summary of your sidekiq workers (based on log file).
Ruby
13
star
32

hasharay_ext

Painless work with complex Ruby hashes/arrays.
Ruby
13
star
33

active_storage_silent_logs

The idea of this gem is to hide as much as possible Active Storage logs from console so you can see only important information and requests
Ruby
13
star
34

rails_cached_method

Simple way to cache results of methods.
Ruby
11
star
35

with_record

Returns relations/association for soft deleted records in DB
Ruby
10
star
36

rrr

Run recent rspec files only (the only recently modified).
Ruby
9
star
37

font_awesome_file_icons

Ruby
4
star
38

unwhere

Ruby
4
star
39

travel_and_talk

JavaScript
3
star
40

lazy_mobile_tester

Rails Lazy Mobile Tester
Ruby
3
star
41

serpjazz

SERP keywords tracking
JavaScript
3
star
42

jeanappv2

JavaScript
2
star
43

slim_erb_backport

Slim 4+ and ERB friends again :)
Ruby
2
star
44

mega-simple-authorization

mega simple authorization plugin for RoR
Ruby
2
star
45

tv

eb5 tv
JavaScript
2
star
46

spring_rspec_commands_addon

rails+spring+rspec = friends :)
Ruby
2
star
47

layouts_from_db_sample

Allow store layouts to DB (Sample)
2
star
48

CheaperDrinker

CheaperDrinker web site
JavaScript
2
star
49

tell_my_env

Ruby
2
star
50

any_login_test

AnyLogin gem test application
Ruby
2
star
51

VerySimple

1
star
52

ShareT

online translations
JavaScript
1
star
53

test-ec2

test-ec2
1
star
54

sa1

1
star
55

better_tempfile

Ruby
1
star
56

ar_enumerations_test_application

ActiveRecord enumeration field type - test application
Ruby
1
star
57

tophouse.com.ua

JavaScript
1
star
58

capistranotest

1
star
59

zip_and_phone

Zips & Phones
Ruby
1
star
60

portfolio

1
star
61

tdemo

tdemo
Ruby
1
star
62

cisarska_and_frankivska

Cisarska & Frankivska
JavaScript
1
star
63

seminars

JavaScript
1
star
64

deprecations_collector

Save all Rails deprecation in log file for future investigation
Ruby
1
star
65

just_for_fun

Do you want to call 42.to_user, [42, 43, 44].to_users? Try this gem :)
Ruby
1
star
66

rails_logs

Ruby
1
star