Skip to content

Instantly share code, notes, and snippets.

@AMHOL
Created April 5, 2016 17:10
Show Gist options
  • Save AMHOL/0671986632fe734189c4c73e2a665f8b to your computer and use it in GitHub Desktop.
Save AMHOL/0671986632fe734189c4c73e2a665f8b to your computer and use it in GitHub Desktop.
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
Copy link
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