Skip to content

Instantly share code, notes, and snippets.

@zdennis
Created March 31, 2021 21:20
Show Gist options
  • Save zdennis/5a6ef6786c79f07e958f68bb865e8c20 to your computer and use it in GitHub Desktop.
Save zdennis/5a6ef6786c79f07e958f68bb865e8c20 to your computer and use it in GitHub Desktop.
Struct That Disallows nil
module StructThatDisallowsNil
def self.new(*args)
Struct.new(*args).tap do |klass|
klass.prepend Module.new {
def initialize(*)
super
members.each do |member|
fail "#{member} cannot be nil" if send(member).nil?
end
end
klass.members.each do |member|
define_method("#{member}=") do |value|
fail "#{member} cannot be nil" if value.nil?
super
end
end
}
end
end
end
YourClass = StructThatDisallowsNil.new(:foo, :bar, keyword_init: true)
YourClass.new(foo: 123, bar: 234) # works
YourClass.new(foo: nil, bar: 234) # fail
yc = YourClass.new(foo: 123, bar: 234)
yc.foo = nil # fail
yc.foo = 234 #works
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment