Skip to content

Instantly share code, notes, and snippets.

@andreaseger
Created September 14, 2016 11:50
Show Gist options
  • Save andreaseger/1fe24ac15d519c6828edf125fa48bdc7 to your computer and use it in GitHub Desktop.
Save andreaseger/1fe24ac15d519c6828edf125fa48bdc7 to your computer and use it in GitHub Desktop.
require 'bundler/inline'
gemfile true do
gem 'dry-types'
end
include Dry::Types.module
class A < Dry::Types::Struct
attribute :a, Strict::Int
end
class AA < A
attribute :aa, Strict::Int
end
class AB < A
attribute :ab, Strict::Int
end
class Foo < Dry::Types::Struct
attribute :bar, A
end
a = A.new(a: 123)
aa = AA.new(a: 123, aa: 234)
ab = AB.new(a: 123, ab: 345)
foo = Foo.new(bar: a)
p [ foo.bar.class,
foo.bar.is_a?(A),
foo.bar.is_a?(AA),
foo.bar.is_a?(AB) ]
# [A, true, false, false]
# everything as expected
foo = Foo.new(bar: aa)
p [ foo.bar.class,
foo.bar.is_a?(A),
foo.bar.is_a?(AA),
foo.bar.is_a?(AB) ]
# [A, true, false, false]
# hmm the type checking worked with subclasses
# but the attribute got somehow coerced? typecasted? type-assigned to it's parent class
foo = Foo.new(bar: ab)
p [ foo.bar.class,
foo.bar.is_a?(A),
foo.bar.is_a?(AA),
foo.bar.is_a?(AB) ]
# [A, true, false, false]
# same as with AA
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment