Created
January 25, 2020 20:38
-
-
Save bryanp/62995e324d2e781e7760ff50be54621e to your computer and use it in GitHub Desktop.
Ruby Monads
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 "dry/monads" | |
include Dry::Monads[:maybe] | |
class Presenter | |
class << self | |
def presents(name, &block) | |
presentations[name] = block | |
end | |
def perform(**presentables) | |
presentables.each_with_object({}) { |(name, value), presented| | |
presented[name] = present(name, value) | |
} | |
end | |
private def presentations | |
@presentations ||= {} | |
end | |
private def present(name, value) | |
if block = presentations[name] | |
block.call(value) | |
else | |
nil | |
end | |
end | |
end | |
end | |
class AddressPresenter < Presenter | |
presents :address do |address| | |
address || "no address" | |
end | |
end | |
AddressPresenter.perform(address: "foo") | |
# => { address: "foo" } | |
AddressPresenter.perform(address: nil) | |
# => { address: "no address" } | |
AddressPresenter.perform(address: Maybe(nil).maybe(&:address)) | |
# { address: None } | |
# Is the correct solution to unwrap the value before passing it along? | |
# | |
AddressPresenter.perform(address: Maybe(nil).maybe(&:address).value_or(nil)) | |
# { address: "no address" } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment