# Evil::Struct

> Nested structure with type constraints for Ruby, based on the dry-initializer DSL

- URL: https://evilmartians.com/opensource/evil-struct
- GitHub: https://github.com/evilmartians/evil-struct
- Authors: Andrew Kozin

---

Evil::Struct is a nested structure with type constraints for Ruby, based on the dry-initializer DSL.

The structure is like [dry-struct](https://dry-rb.org/gems/dry-struct/main/), except it controls optional attributes and default values aside of type constraints.

Its DSL is taken from [dry-initializer](https://evilmartians.com/opensource/dry-initializer). Its method `attribute` is just an alias for `option`.

```ruby
require "evil-struct"
require "dry-types"

class Product < Evil::Struct
  attribute :title
  attribute :price,    Dry::Types["coercible.float"]
  attribute :quantity, Dry::Types["coercible.int"], default: proc { 0 }

  # shared options
  attributes optional: true do
    attribute :subtitle
    attribute :description
  end
end

# Accepts both symbolic and string keys.
# Class methods `[]`, `call`, and `load` are just aliases for `new`
product = Product[title: "apple", "price" => "10.9", description: "a fruit"]

# Attributes are available via methods or `[]`
product.title       # => "apple"
product[:price]     # => 10.9
product["quantity"] # => 0
product.description # => "a fruit"

# unassigned value differs from `nil`
product.subtitle    # => Dry::Initializer::UNDEFINED

# Raises in case a mandatory value was not assigned
Product.new # BOOM! because neither title, nor price are assigned

# Hashifies all attributes except for undefined subtitle
# You can use `dump` as an alias for `to_h`
product.to_h
# => { title: "apple", price: 10.9, description: "a fruit", quantity: 0 }

# The structure is comparable to any object that responds to `#to_h`
product == { title: "apple", price: 10.9, description: "a fruit", quantity: 0 }
# => true
```
