Created
June 19, 2015 22:46
-
-
Save wojtha/0e962d9cbf8c32c35dce to your computer and use it in GitHub Desktop.
Ruby nil objects in response to https://rishionrails.wordpress.com/2015/05/25/using-null-object-pattern-in-rails-to-improve-code-quality
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
# Empty methods returns nil implicitly: | |
class NilInspectionResult | |
def gage_serial_number; end | |
def inspected_by; end | |
def inspected_on_rep; end | |
def remarks; end | |
def non_conformance_number; end | |
end | |
# Or we can use attr_reader as a shorthand: | |
class NilInspectionResult | |
attr_reader :gage_serial_number, | |
:inspected_by, | |
:inspected_on_rep, | |
:remarks, | |
:non_conformance_number | |
end | |
# Structs seems to be best for creating null objets: | |
NilInspectionResult = Struct.new( | |
:gage_serial_number, | |
:inspected_by, | |
:inspected_on_rep, | |
:remarks, | |
:non_conformance_number | |
) | |
# Alternative syntax with some not nil method: | |
class NilInspectionResult < Struct.new( | |
:gage_serial_number, | |
:inspected_by, | |
:inspected_on_rep, | |
:remarks, | |
:non_conformance_number | |
) | |
def some_not_nil_method | |
"not nil" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment