Skip to content

Instantly share code, notes, and snippets.

@apneadiving
Last active October 24, 2016 13:05
Show Gist options
  • Save apneadiving/289b70ef3fb5f28188e91cd10f6bbf45 to your computer and use it in GitHub Desktop.
Save apneadiving/289b70ef3fb5f28188e91cd10f6bbf45 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'monadic'
class MonadicService
def initialize(user_id)
@user_id = user_id
end
def call
response = HTTParty.get("https://jsonplaceholder.typicode.com/users/#{@user_id}")
if response.code == 200
Success(response.body)
else
Failure("Error status #{response.code}")
end
end
end
# goal: print the outcome for:
# - one single call
# - two calls in a row
Success({})
.bind { MonadicService.new(42).call) }
.bind {|result| puts(result); true } # last true statement feels lame
.or {|error| puts(error); false } # last false statement feels lame
Success({})
.bind {|hash| MonadicService.new(12).call.bind {|r| hash.merge({ value1: r })}}
.bind {|hash| MonadicService.new(14).call.bind {|r| hash.merge({ value2: r })}}
.bind {|hash| puts(hash[:value1], hash[:value2]); true }
.or {|error| puts(error); false }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment