Skip to content

Commit

Permalink
Add Namespace.traverse
Browse files Browse the repository at this point in the history
  • Loading branch information
marcandre committed Sep 24, 2018
1 parent b22b66a commit de6b887
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
16 changes: 16 additions & 0 deletions lib/tlaw/namespace.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,22 @@ def base_url=(url)
end
end

RESTRICTION = {
endpoints: Endpoint,
namespaces: Namespace,
nil => APIPath
}.freeze

def traverse(restrict_to = nil, &block)
return to_enum(:traverse, restrict_to) unless block_given?
klass = RESTRICTION.fetch(restrict_to)
children.each do |_, child|
yield child if child < klass
child.traverse(restrict_to, &block) if child.respond_to?(:traverse)
end
self
end

# Lists all current namespace's nested namespaces as a hash.
#
# @return [Hash{Symbol => Namespace}]
Expand Down
41 changes: 41 additions & 0 deletions spec/tlaw/namespace_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,26 @@ module TLAW
}
}

let(:child_endpoint_class) {
Class.new(Endpoint).tap { |c|
c.symbol = :child_ep
c.path = '/child_ep'
}
}

let(:grand_child_class) {
Class.new(described_class).tap { |c|
c.symbol = :grand_child_ns
c.path = '/ns3'
}
}

let(:child_class) {
Class.new(described_class).tap { |c|
c.symbol = :child_ns
c.path = '/ns2'
c.add_child child_endpoint_class
c.add_child grand_child_class
}
}

Expand Down Expand Up @@ -91,6 +107,31 @@ module TLAW
| .some_ep(foo: nil)
}.unindent)}
end

context '.traverse' do
it 'can yield all children recursively' do
expect(namespace_class.traverse.to_a).to eq [
endpoint_class,
child_class,
child_endpoint_class,
grand_child_class
]
end

it 'can yield all endpoints recursively' do
expect(namespace_class.traverse(:endpoints).to_a).to eq [
endpoint_class,
child_endpoint_class
]
end

it 'can yield all namespaces recursively' do
expect(namespace_class.traverse(:namespaces).to_a).to eq [
child_class,
grand_child_class
]
end
end
end

context 'instance' do
Expand Down

0 comments on commit de6b887

Please sign in to comment.