Last active
January 4, 2016 20:49
-
-
Save jwilger/8676700 to your computer and use it in GitHub Desktop.
Good idea for eliminating nil checks?
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
require 'pass_to' | |
class Page | |
attr_reader :content | |
def initialize(content = nil) | |
@content = content | |
end | |
def print | |
content.pass_to(method(:print_content), otherwise: method(:print_no_content)) | |
end | |
private | |
def print_content(content) | |
puts content | |
end | |
def print_no_content | |
puts "This Page Left Intentionally Blank" | |
end | |
end | |
class Image | |
attr_reader :size | |
def initialize(size) | |
@size = size | |
end | |
def blank? | |
size == 0 | |
end | |
def pass_to(message, otherwise: ->{}) | |
blank? ? otherwise.call : message.call(self) | |
end | |
end | |
document = [ | |
Page.new("This is page 1"), | |
Page.new, | |
Page.new("This is page 3; page 2 was blank."), | |
Page.new(Image.new(10)), | |
Page.new(Image.new(0)) | |
] | |
document.each { |p| p.print } |
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
class Object | |
def pass_to(message, otherwise: ->{}) | |
message.call(self) | |
end | |
end | |
class NilClass | |
def pass_to(message, otherwise: ->{}) | |
otherwise.call | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment