Skip to content

Instantly share code, notes, and snippets.

@fgarcia
Last active March 20, 2016 22:32
Show Gist options
  • Save fgarcia/792add55aee5751ef32b to your computer and use it in GitHub Desktop.
Save fgarcia/792add55aee5751ef32b to your computer and use it in GitHub Desktop.
On Dry types

Should a dry type behave more like a Hash?

Goal: ease transition / refactoring of existing code base

Functions like .keys, .values, .map are missing

Having them would make Dry Structs/Values a perfect drop-in replacement for Hash objects

Maybe a standard mixin to "extend this dirty functionality" would be great Any reason why those functions are not provided? It would be the most Ruby idiomatic

Why values with nil are required?

class User < Dry::Types::Struct
  attribute :name, Types::Maybe::Coercible::String
  attribute :age, Types::Coercible::Int
end

user = User.new(name: nil, age: '21')  # OK
user = User.new(age: '21')             # FAIL

Optional types (Maybe) do require the initializing hash to specify a nil value. Why?

This seems like a common initialization pattern that will be needed

input = Hash.new (....)
hash_with_nils = Hash[ User.schema.keys.map { |k| [k, nil] } ]
hash_with_nils.merge(input)
@solnic
Copy link

solnic commented Mar 20, 2016

You can do:

class User < Dry::Types::Struct
  constructor_type :schema

  # ...
end

This will assume nil as the default value for missing keys.

Re hash-like interface, I wouldn't like that. One could easily do it with a custom extension, but I don't want to maintain this in dry-types project. Also notice that structs and values are coercible to a hash, so in places where your code expects a hash, you can just do Hash(object).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment