Skip to content

Commit

Permalink
Implement enumerable for has_content module (#7)
Browse files Browse the repository at this point in the history
  • Loading branch information
chadwilken authored Nov 1, 2023
1 parent 8dd16bf commit 68d488a
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 7 deletions.
16 changes: 14 additions & 2 deletions lib/tip_tap/has_content.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

module TipTap
module HasContent
include Enumerable

attr_reader :attrs, :content

def self.included(base)
Expand All @@ -20,13 +22,23 @@ def initialize(content = [], **attributes)
yield self if block_given?
end

def find_node(node_type)
content.find { |child| child.is_a?(node_type) }
def each
content.each { |child| yield child }
end

def find_node(type_class_or_name)
node_type = type_class_or_name.is_a?(String) ? TipTap.node_for(type_class_or_name) : type_class_or_name
find { |child| child.is_a?(node_type) }
end

def add_content(node)
@content << node
end
alias_method :<<, :add_content

def size
content.size
end

module ClassMethods
# Create a new instance from a TipTap JSON object.
Expand Down
47 changes: 42 additions & 5 deletions spec/tip_tap/document_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -80,13 +80,50 @@
end
end

describe "Enumerable" do
it "iterates over the content for #each" do
json = {
type: "doc",
content: [
{
type: "paragraph",
content: [
{
type: "text",
text: "Hello World!",
marks: [
{type: "bold"},
{type: "italic"}
]
}
]
}
]
}
document = TipTap::Document.from_json(json)
expect(document.map(&:class)).to eq([TipTap::Nodes::Paragraph])
end
end

describe "find_node" do
it "returns a node" do
document = TipTap::Document.from_json(json_contents)
node = document.find_node(TipTap::Nodes::Paragraph)
context "when passing a string" do
it "returns a node" do
document = TipTap::Document.from_json(json_contents)
node = document.find_node(TipTap::Nodes::Paragraph.type_name)

expect(node).to be_a(TipTap::Nodes::Paragraph)
expect(node.to_plain_text).to eq("Hello World!")
end
end

context "when passing a class" do
it "returns a node" do
document = TipTap::Document.from_json(json_contents)
node = document.find_node(TipTap::Nodes::Paragraph)

expect(node).to be_a(TipTap::Nodes::Paragraph)
expect(node.to_plain_text).to eq("Hello World!")
expect(node).to be_a(TipTap::Nodes::Paragraph)
expect(node.to_plain_text).to eq("Hello World!")
end
end
end

Expand Down

0 comments on commit 68d488a

Please sign in to comment.