Class: EditorJs::Document

Inherits:
Object
  • Object
show all
Defined in:
lib/editor_js/document.rb

Constant Summary collapse

SCHEMA =
YAML.safe_load(<<~YAML)
  type: object
  additionalProperties: false
  properties:
    time:
      type: number
    blocks:
      type: array
      items:
        type: object
    version:
      type: string
  required:
  - time
  - blocks
  - version
YAML

Instance Method Summary collapse

Constructor Details

#initialize(str_or_hash, invalid_block_renderer: nil) ⇒ Document

Returns a new instance of Document.



24
25
26
27
28
29
# File 'lib/editor_js/document.rb', line 24

def initialize(str_or_hash, invalid_block_renderer: nil)
  str_or_hash = JSON.parse(str_or_hash) unless str_or_hash.is_a?(Hash)
  @invalid_block_renderer = invalid_block_renderer
  @content = str_or_hash
  @blocks = []
end

Instance Method Details

#outputObject



58
59
60
61
62
# File 'lib/editor_js/document.rb', line 58

def output
  return @output if instance_variable_defined?(:@output)

  @output = valid? ? @content.merge('blocks' => @blocks.map(&:output)) : {}
end

#plainObject



50
51
52
53
54
55
56
# File 'lib/editor_js/document.rb', line 50

def plain
  return @renderred_plain if instance_variable_defined?(:@renderred_plain)

  @renderred_plain = valid? && @blocks.map(&:plain).select do |text|
    text if text.present?
  end.join('. ') || ''
end

#renderObject



44
45
46
47
48
# File 'lib/editor_js/document.rb', line 44

def render
  return @renderred_html if instance_variable_defined?(:@renderred_html)

  @renderred_html = valid? ? @blocks.map(&:render).join.html_safe : ''
end

#valid?Boolean

Returns:

  • (Boolean)


31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/editor_js/document.rb', line 31

def valid?
  return @valid if instance_variable_defined?(:@valid)

  @valid = JSON::Validator.validate(SCHEMA, @content)
  return false unless @valid

  @blocks = @content['blocks'].map do |blk_data|
    blk = EditorJs::Blocks::Base.load(blk_data)
    blk.valid? ? blk : @invalid_block_renderer&.new(blk_data)
  end.compact
  @valid = @blocks.count.positive?
end