Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
require 'dry-types'
class Carrier
attr_reader :name
def initialize(attributes)
@name = attributes.fetch(:name)
end
end
class Delivery
attr_reader :reference
def initialize(attributes)
@reference = attributes.fetch(:reference)
end
end
Dry::Types.register_class(Carrier)
Dry::Types.register_class(Delivery)
module Types
include Dry::Types.module
end
class Assignment < Dry::Types::Struct
attribute :delivery, Types::Delivery
attribute :carrier, Types::Carrier
attribute :created_at, Types::Maybe::Strict::Time
end
Assignment.new(delivery: { reference: '1337' }, carrier: { name: 'O2' }, created_at: nil)
# => #<Assignment delivery=#<Delivery:0x0055fbef85ad90 @reference="1337"> carrier=#<Carrier:0x0055fbef85ad40 @name="O2"> created_at=None>
@AMHOL

This comment has been minimized.

Copy link
Owner Author

AMHOL commented Apr 5, 2016

require 'dry-types'

# Register ActiveRecord subclasses with dry-types
module Dry
  module ActiveRecord
    module Registry
      def inherited(subclass)
        Dry::Types.register_class(subclass)
        super(subclass)
      end
    end
  end
end

ActiveRecord::Base.__send__(:extend, Dry::ActiveRecord::Registry)

class Carrier < ActiveRecord::Base; end

class Delivery < ActiveRecord::Base; end

module Types
  include Dry::Types.module
end

class Assignment < Dry::Types::Struct
  attribute :delivery, Types::Delivery
  attribute :carrier, Types::Carrier
  attribute :created_at, Types::Maybe::Strict::Time
end

Assignment.new(delivery: { reference: '1337' }, carrier: { name: 'O2' }, created_at: nil)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.