Skip to content

Commit ca00846

Browse files
committed
Add methods for introspection Struct attributes
closes #45
1 parent 0d87191 commit ca00846

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

lib/dry/struct/class_interface.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,21 @@ def primitive
187187
def optional?
188188
false
189189
end
190+
191+
# Checks if this {Struct} has the given attribute
192+
#
193+
# @param [Symbol] key Attribute name
194+
# @return [Boolean]
195+
def attribute?(key)
196+
schema.key?(key)
197+
end
198+
199+
# Gets the list of attribute names
200+
#
201+
# @return [Array<Symbol>]
202+
def attribute_names
203+
schema.keys
204+
end
190205
end
191206
end
192207
end

spec/shared/struct.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,19 @@
133133
expect { optional_type[foo: :bar] }.to raise_error(Dry::Types::ConstraintError)
134134
end
135135
end
136+
137+
describe '.attribute?' do
138+
it 'checks if a struct has an attribute' do
139+
expect(type.attribute?(:name)).to be true
140+
expect(type.attribute?(:last_name)).to be false
141+
end
142+
end
143+
144+
describe '.attribute_names' do
145+
it 'returns the list of schema keys' do
146+
expect(type.attribute_names).to eql(%i(name age address root))
147+
end
148+
end
136149
end
137150

138151
it 'registered without wrapping' do

0 commit comments

Comments
 (0)