EditorjsRenderer
EditorjsRenderer is a Ruby gem that brings Editor.js support to Rails applications.
It allows rendering JSON data generated by Editor.js into safe HTML and plain text.
Features
- Support for structured content (Editor.js blocks)
- Built-in validation using JSON Schema
- Secure HTML output via escaping
- Configurable block rendering system
- Support for nested blocks (blocks within blocks)
- Blocks:
Spoiler
,Table
,Checklist
,Attaches
,Code
,Delimiter
, etc. - No JavaScript dependencies required on the server side
Installation
Add this line to your Gemfile:
gem "editorjs_renderer"
And then execute:
bundle install
Usage
data = {
"time" => "123456789",
"blocks" => [
{ "type" => "paragraph", "data" => { "text" => "Hello <b>world</b>" } },
{ "type" => "checklist", "data" => { "items" => [
{ "text" => "Buy milk", "checked" => true },
{ "text" => "Read book", "checked" => false }
]}
}
]
}
document = EditorjsRenderer::Document.new(data)
document.render(format: :html)
# => "<p>Hello <b>world</b></p><ul class=\"checklist-block\"><li><input type=\"checkbox\" checked disabled> Buy milk</li><li><input type=\"checkbox\" disabled> Read book</li></ul>"
document.render(format: :plain)
# => "Hello <b>world</b>\n[x] Buy milk\n[ ] Read book"
Configuration
The gem includes a default schema for the paragraph
block, located at:
lib/editorjs_renderer/schemas/
You can configure enabled block types and schema path:
EditorjsRenderer.configure do |config|
config.enabled_blocks = %w[paragraph]
config.schemas_path = Rails.root.join("config/editor_schemas").to_s
end
Schemas should follow the JSON Schema format and be stored in YAML files. Each block must have a schema named like paragraph.yml, header.yml, etc.
Example:
type: object
required:
- text
properties:
text:
type: string
description: "The main content of the header block"
In this schema:
-
text
is a required field of type string, which represents the header text.
Development
To run tests and linters:
bundle exec rake
Rendering Custom Blocks
To support a new block:
- Create a class in EditorjsRenderer::Blocks namespace (e.g., Header)
- Inherit from EditorjsRenderer::Blocks::Base
- Implement render and plain
- Add a corresponding schema
module EditorjsRenderer
module Blocks
class Header < Base
def render
"<h1>#{ERB::Util.html_escape(data["text"])}</h1>"
end
def plain
data["text"].to_s
end
end
end
end
Autoloading with Zeitwerk
This gem uses Zeitwerk to handle autoloading. Ensure you have Zeitwerk set up in your environment:
require "zeitwerk"
loader = Zeitwerk::Loader.for_gem
loader.setup
Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/lordsynergy/editorjs_renderer.
License
This gem is licensed under the MIT License.