File tree Expand file tree Collapse file tree
lib/studitemps/utils/uri/extensions Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -93,6 +93,15 @@ InvoiceTypeURI.build('com.example:billing:invoice:pro_forma') # => Sry::Types::C
9393InvoiceTypeURI .new (id: ' 1042' ) # => #<InvoiceTypeURI 'com.example:billing:invoice:1024'>
9494InvoiceTypeURI .new (id: ' pro_forma' ) # => Dry::Types::ConstraintError
9595
96+ # and this can be used in sum types to coerce *distinct* IDs to the correct URI
97+ ltype = Dry .Types ::Coercible ::Integer .constrained(lt: 1000 )
98+ LegacyInvoiceTypeURI = Studitemps ::Utils ::URI .build(from: InvoiceURI , context: ' legacy_invoice' , id: ltype)
99+
100+ InvoiceSumType = InvoiceTypeURI ::Types ::URI | LegacyInvoiceTypeURI ::Types ::URI
101+
102+ InvoiceSumType [id: 23 ] # => #<LegacyInvoiceTypeURI 'com.example:legacy_invoice:invoice:23'>
103+ InvoiceSumType [id: 1023 ] # => #<InvoiceTypeURI 'com.example:billing:invoice:1023'>
104+ InvoiceSumType [id: ' x' ] # => Dry::Types::CoercionError
96105```
97106
98107### Extensions
Original file line number Diff line number Diff line change @@ -26,11 +26,21 @@ module Extensions
2626 # URI = ::MyURI::Types::URI
2727 # end
2828 module Types
29+ module RescueConstraintError
30+ def build ( *_args , **_kwargs , &_block )
31+ super
32+ rescue Dry ::Types ::ConstraintError => e
33+ raise Studitemps ::Utils ::URI ::Base ::InvalidURI , e
34+ end
35+ end
36+
2937 ::Studitemps ::Utils ::URI ::Builder . extensions << -> ( klass ) {
3038 types = Module . new
3139 types . const_set 'URI' , Dry . Types . Constructor ( klass ) { |value | klass . build ( value ) }
3240 types . const_set 'String' , Dry . Types . Constructor ( String ) { |value | klass . build ( value ) . to_s }
3341 klass . const_set 'Types' , types
42+
43+ klass . extend ( RescueConstraintError )
3444 }
3545
3646 end
Original file line number Diff line number Diff line change @@ -499,7 +499,23 @@ module Utils # rubocop:disable Metrics/ModuleLength
499499
500500 expect {
501501 invoice_klass . build ( 'com.example:billing:invoice:23' )
502- } . to raise_error Dry ::Types ::ConstraintError
502+ } . to raise_error Studitemps ::Utils ::URI ::Base ::InvalidURI
503+ end
504+
505+ it 'supports sum types' do
506+ legacy_invoice_number_type = Dry . Types ::Coercible ::Integer . constrained ( lt : 1000 )
507+ legacy_invoice_klass = URI . build (
508+ from : klass , resource : 'legacy_invoice' , id : legacy_invoice_number_type
509+ )
510+
511+ sum_type = legacy_invoice_klass ::Types ::URI | invoice_klass ::Types ::URI
512+
513+ expect ( sum_type [ id : 23 ] ) . to eq legacy_invoice_klass . new ( id : 23 )
514+ expect ( sum_type [ id : 1023 ] ) . to eq invoice_klass . new ( id : 1023 )
515+
516+ expect {
517+ sum_type [ id : '<invalid>' ]
518+ } . to raise_error Dry ::Types ::CoercionError
503519 end
504520 end
505521 end
You can’t perform that action at this time.
0 commit comments