Sha256: ff1735bf2a88f27fa3173a73390f9f1b2c6b8f90f9754f919d7d40c233e6f818

Contents?: true

Size: 1.48 KB

Versions: 12

Compression:

Stored size: 1.48 KB

Contents

require 'json'
require 'yaml'

module EditorJs
  class Document
    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

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

    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|
        EditorJs::Blocks::Base.load(blk_data)
      end
      @valid = blocks.all?(&:valid?)
      @blocks = blocks if @valid
      @valid
    end

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

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

    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

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

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

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
editor_js-0.3.6.1 lib/editor_js/document.rb
editor_js-0.3.5.1 lib/editor_js/document.rb
editor_js-0.3.6 lib/editor_js/document.rb
editor_js-0.3.5 lib/editor_js/document.rb
editor_js-0.3.3 lib/editor_js/document.rb
editor_js-0.3.2 lib/editor_js/document.rb
editor_js-0.3.1 lib/editor_js/document.rb
editor_js-0.3.0 lib/editor_js/document.rb
editor_js-0.2.5 lib/editor_js/document.rb
editor_js-0.2.4 lib/editor_js/document.rb
editor_js-0.2.3 lib/editor_js/document.rb
editor_js-0.2.2 lib/editor_js/document.rb