Types code organization

I’m heavily pushing dry-types where I work because I feel that is providing a lot of value understanding the data structures we handle.
Now I’ve been going back and forward on how to organize the types in a clean way trying to avoid duplication.

So far most of our types live in lib/types.rb but there are some specific implementations that usually just exist on the file using it

Example

module Types
  include Dry.Types()

  Type = Types.Instance(Dry::Types::Type)
  SquishedString = Types::Coercible::String >> :squish.to_proc
end

class SomeService
  Input = Types::Array.of(Types::SquishedString)

  def self.call(input)
    Input[input].map #...
  end
end

I can’t really think of a clean way to organize general types are more specific ones trying to prevent duplication.
I thought of a lib/types/#{specific_type} kind of thing but I don’t love it. I just want to get a clean organization without having to jump many hoops.

What are your preferred techniques to organize types in a codebase?
Thanks!

Recommend you define your types module first, before opening it. This allows you to reopen nested modules.

Types = Dry.Types()

module Types
  module Coercible
    SquishedString = String.constructor(&:squish)
  end
end

I use types extensively, and organize them exactly the way you describe. I think having to look in more places for them would only make it harder to understand.

1 Like

Thanks for the tip!
I’ve been doing ↓ but your version makes more sense

module Types
  include Dry.Types()

  Coercible::Potato = Types::Symbol #...
end