Class: Coradoc::Markdown::Base

Inherits:
Lutaml::Model::Serializable
  • Object
show all
Defined in:
lib/coradoc/markdown/model/base.rb

Overview

Base class for all Markdown model objects.

The Base class provides common functionality for all document model elements, including serialization support and tree traversal.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.visit(element) {|element, :post| ... } ⇒ Object

Visit pattern for traversing the document tree

Yields:

  • (element, :post)


25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/coradoc/markdown/model/base.rb', line 25

def self.visit(element, &block)
  return element if element.nil?

  element = yield element, :pre
  element = case element
            when self
              element.visit(&block)
            when Array
              element.map { |child| visit(child, &block) }.flatten.compact
            when Hash
              result = {}
              element.each { |k, v| result[k] = visit(v, &block) }
              result
            else
              element
            end
  yield element, :post
end

Instance Method Details

#serialize_content(content) ⇒ Object

Serialize polymorphic content to Markdown string



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/coradoc/markdown/model/base.rb', line 54

def serialize_content(content)
  case content
  when Array
    content.map { |elem| serialize_content(elem) }.join
  when String
    content
  when nil
    ''
  else
    if content.is_a?(Base)
      content.to_md
    else
      raise ArgumentError,
            "Cannot serialize #{content.class.name} to Markdown. " \
            'Expected String or Base subclass.'
    end
  end
end

#to_hObject

Does a shallow attribute dump of the object



74
75
76
77
78
# File 'lib/coradoc/markdown/model/base.rb', line 74

def to_h
  self.class.attributes.keys.each_with_object({}) do |attribute, acc|
    acc[attribute] = public_send(attribute)
  end
end

#to_mdObject

Serialize this model element to Markdown



81
82
83
# File 'lib/coradoc/markdown/model/base.rb', line 81

def to_md
  Coradoc::Markdown::Serializer.serialize(self)
end

#visit(&block) ⇒ Object



44
45
46
47
48
49
50
51
# File 'lib/coradoc/markdown/model/base.rb', line 44

def visit(&block)
  self.class.attributes.each_key do |attr_name|
    child = public_send(attr_name)
    result = self.class.visit(child, &block)
    public_send(:"#{attr_name}=", result) if result != child
  end
  self
end