Created
March 31, 2021 21:20
-
-
Save zdennis/5a6ef6786c79f07e958f68bb865e8c20 to your computer and use it in GitHub Desktop.
Struct That Disallows nil
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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