Skip to content

Instantly share code, notes, and snippets.

@jwilger
Last active January 4, 2016 20:49
Show Gist options
  • Save jwilger/8676700 to your computer and use it in GitHub Desktop.
Save jwilger/8676700 to your computer and use it in GitHub Desktop.
Good idea for eliminating nil checks?
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 }
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