Skip to content

Commit

Permalink
Add Namespace.traverse
Browse files Browse the repository at this point in the history
  • Loading branch information
marcandre committed Oct 8, 2018
1 parent f1255ed commit c76e0af
Show file tree
Hide file tree
Showing 2 changed files with 58 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
42 changes: 42 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,32 @@ module TLAW
| .some_ep(foo: nil)
}.unindent)}
end

context '.traverse' do
subject { ->(*args) { namespace_class.traverse(*args).to_a } }

it { is_expected.to ret [
endpoint_class,
child_class,
child_endpoint_class,
grand_child_class
]
}

its_call(:endpoints) { is_expected.to ret [
endpoint_class,
child_endpoint_class
]
}

its_call(:namespaces) { is_expected.to ret [
child_class,
grand_child_class
]
}

its_call(:garbage) { is_expected.to raise_error KeyError }
end
end

context 'instance' do
Expand Down

0 comments on commit c76e0af

Please sign in to comment.