dry-initializer

Introduction & Usage

dry-initializer is a simple mixin of class methods params and options for instances.

Synopsis

require 'dry-initializer'
require 'dry-types'

class User
  extend Dry::Initializer

  param  :name,  Dry::Types['strict.string']
  param  :role,  default: proc { 'customer' }
  option :admin, default: proc { false }
end

user = User.new 'Vladimir', 'admin', admin: true

user.name  # => 'Vladimir'
user.role  # => 'admin'
user.admin # => true

This is pretty the same as the following ruby code:

class User
  attr_reader :name, :role, :admin

  def initialize(name = Dry::Initializer::UNDEFINED, role = 'customer', **__options__)
    @name  = Dry::Types['strict.string'][name]
    @role  = role
    @admin = __options__.fetch(:admin, Dry::Initializer::UNDEFINED)
  end
end