Created
January 10, 2012 21:57
-
-
Save austintaylor/1591452 to your computer and use it in GitHub Desktop.
Needing the `Either a` monad in Ruby
This file contains hidden or 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
loadStuff :: Map -> Either String (ThingOne, ThingTwo) | |
loadStuff params = do | |
thingOne <- loadThingOne params | |
thingTwo <- loadThingTwo params thingOne | |
checkSomething thingTwo | |
return (thingOne, thingTwo) |
This file contains hidden or 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
def load_stuff(params) | |
thing_one, error = load_thing_one(params) | |
return [nil, nil, error] unless thing_one | |
thing_two, error = load_thing_two(params, thing_one) | |
return [nil, nil, error] unless thing_two | |
error = check_something(thing_two) | |
return [nil, nil, error] if error | |
[thing_one, thing_two, nil] | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think this is the best way to do this in Ruby. There was a bunch of duplicated error/success handling code (modify session, redirect, etc), which needed to be extracted so that the loading part could be reused. A more imperative solution would be to push the outcome code down into methods, and then override those methods (the inheritance approach) or to move them into a delegate (the Objective-C approach).