dry-types

v1.8 v1.7
  1. Introduction
  2. Getting Started
  3. Built-in Types
  4. Type Attributes
  5. Default Values
  6. Fallbacks
  7. Sum
  8. Constraints
  9. Hash Schemas
  10. Array With Member
  11. Enum
  12. Map
  13. Custom Types
  14. Custom Type Builders
  15. Extensions
    1. Maybe
    2. Monads

TOC

  1. Using Dry::Types in Your Application
  2. Creating Your First Type

Getting Started

Using Dry::Types in Your Application

  1. Make Dry::Types available to the application by creating a namespace that includes Dry::Types:

    module Types
     include Dry.Types()
    end
    
  2. Reload the environment, & type Types::Coercible::String in the ruby console to confirm it worked:

    Types::Coercible::String
    # => #<Dry::Types::Constructor type=#<Dry::Types::Definition primitive=String options={}>>
    

Creating Your First Type

  1. Define a struct's types by passing the name & type to the attribute method:

    class User < Dry::Struct
      attribute :name, Types::String
    end
    
  2. Define Custom Types in the Types module, then pass the name & type to attribute:

    module Types
      include Dry.Types()
    
      Email = String.constrained(format: /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i)
      Age = Integer.constrained(gt: 18)
    end
    class User < Dry::Struct
      attribute :name, Types::String
      attribute :email, Types::Email
      attribute :age, Types::Age
    end
    
  3. Use a Dry::Struct as a type:

    class Message < Dry::Struct
      attribute :body, Types::String
      attribute :to, User
    end