Coercing to domain model

Hi,

I’m struggling to solve following problem: client sends uuid of domain model to my app. I’d like to coerce this to AR record (query database for uuid column), or nil - if no record found. How to approch that problem using dry-types? I’ve found a lot of examples how to modify available types, but none how to make your own type from scratch. Can you help with some example?

Greg

Hey,

I don’t think that this is a good use case for a dry type object but this could be done like that:

module Types
  include Dry::Types.module

  SomeModelFromUUID = Dry::Types::Definition.new(SomeModel).constructor do |uuid|
    SomeModel.find_by(uuid: uuid)
  end
end

Types::SomeModelFromUUID["04953F81-4621-423F-892A-07CAB33B47E9"]
# returns SomeModel instance or nil

Hope this is helps
Cheers :slight_smile:

1 Like