Skip to content

Instantly share code, notes, and snippets.

View vitaly-pushkar's full-sized avatar

Vitaly Pushkar vitaly-pushkar

View GitHub Profile
@vitaly-pushkar
vitaly-pushkar / db_setup.rb
Created January 23, 2020 20:04
From the blog post "Error Handling with Either Monads in Ruby"
ActiveRecord::Base.establish_connection( adapter: 'sqlite3', database: ":memory:" )
ActiveRecord::Schema.define(version: 1) { create_table(:users) { |t| t.string :name; t.string :email } }
class User < ActiveRecord::Base; end
User.create(name: 'Vitaly', email: 'vitaly.pushkar@gmail.com')
@vitaly-pushkar
vitaly-pushkar / do_notation.rb
Created January 23, 2020 20:05
From the blog post "Error Handling with Either Monads in Ruby"
def call(fields)
fields = yield validate_fields(fields)
email = yield validate_email(fields['email'])
user = yield find_user(fields['id'])
user = yield update_user(user, {name: fields['name'], email: fields['email']})
sent = yield send_email(user, :profile_updated)
Success(user)
end
@vitaly-pushkar
vitaly-pushkar / try_monad.rb
Created January 23, 2020 20:06
From the blog post "Error Handling with Either Monads in Ruby"
def find_user(id)
Try { user_model.find_by(id: id) }
end
def update_user(user, data)
Try do
user.update(data)
user.reload
end
end
@vitaly-pushkar
vitaly-pushkar / endpoint.rb
Last active January 31, 2020 21:22
From the blog post "Error Handling with Either Monads in Ruby"
patch '/users/:id/' do
result = UserUpdater.new(User, config.mailer).call(params).to_result
# a simple, "unambitious" version
if result.success?
result.sucess.to_json
else
{error: result.failure}.to_json
end
end
# Enable Powerlevel10k instant prompt. Should stay close to the top of ~/.zshrc.
# Initialization code that may require console input (password prompts, [y/n]
# confirmations, etc.) must go above this block; everything else may go below.
if [[ -r "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh" ]]; then
source "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh"
fi
source "${HOME}/.zgen/zgen.zsh"
#if the init script doesn't exist