Class: RicherText::Node

Inherits:
Object
  • Object
show all
Includes:
Rendering
Defined in:
lib/richer_text/node.rb

Constant Summary collapse

STYLES =
{
  "textAlign" => "text-align"
}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(json) ⇒ Node

Returns a new instance of Node.



16
17
18
19
20
21
# File 'lib/richer_text/node.rb', line 16

def initialize(json)
  @json = json
  @attrs = json.fetch("attrs", {})
  @type = json.fetch("type", "text")
  @children = json.fetch("content", []).map { |child| self.class.build(child) }
end

Instance Attribute Details

#attrsObject (readonly)

Returns the value of attribute attrs.



3
4
5
# File 'lib/richer_text/node.rb', line 3

def attrs
  @attrs
end

#childrenObject (readonly)

Returns the value of attribute children.



3
4
5
# File 'lib/richer_text/node.rb', line 3

def children
  @children
end

#jsonObject (readonly)

Returns the value of attribute json.



3
4
5
# File 'lib/richer_text/node.rb', line 3

def json
  @json
end

#typeObject (readonly)

Returns the value of attribute type.



3
4
5
# File 'lib/richer_text/node.rb', line 3

def type
  @type
end

Class Method Details

.build(json) ⇒ Object



10
11
12
13
14
# File 'lib/richer_text/node.rb', line 10

def self.build(json)
  node = json.is_a?(String) ? JSON.parse(json) : json
  klass = "RicherText::Nodes::#{node["type"].underscore.classify}".constantize
  klass.new(node) if klass
end

Instance Method Details

#accept(visitor) ⇒ Object



27
28
29
# File 'lib/richer_text/node.rb', line 27

def accept(visitor)
  visitor.send("visit_#{type.underscore}", self)
end

#styleObject



23
24
25
# File 'lib/richer_text/node.rb', line 23

def style
  @attrs.select { |k, v| STYLES.key?(k) }.map { |k, v| "#{STYLES[k]}: #{v};" }.join
end