Skip to content

Instantly share code, notes, and snippets.

View topherhunt's full-sized avatar
🦕

Topher Hunt topherhunt

🦕
View GitHub Profile
@topherhunt
topherhunt / auth_plugs.ex
Created October 18, 2019 15:24
Auth plug load_current_user using cond vs. with
# These aren't 100% parallel (they're from different apps with slightly different auth rules)
# but they're close enough to demonstrate what `with` can do, I think.
# Version 1: using `cond`
# Pro: very linear. just go down the list and pick the first truthy result.
# Con: Using `cond` maybe doesn't sufficiently emphasize how important the ordering is
# here. If you naively swapped the order of two conditions, it could wreck the security.
# Basically, in this version, I'm relying on the dev's caution and willingness to read
# through my extensive comments.
def load_current_user(conn, _opts) do
@topherhunt
topherhunt / four_approaches.ex
Last active October 18, 2019 06:58
Four approaches to expressing nested logic
defmodule Sample do
#
# VERSION 1
# The naive approach: just nest the if/else statements. Pretty readable.
#
def custom_block(project, label) do
# ... validations ...
if project do
if block = Enum.find(project.custom_blocks, & &1.label == label) do
# Rid your codebase of haml templates.
# Requires Calliope as a dependency in your Mix project.
# Usage: `mix run haml.exs path/to/my/haml/file.html.haml
# It will spit out the produced eex, which you can copy & paste into place.
path = System.argv() |> Enum.at(0)
{:ok, haml} = File.read(path)
IO.puts ""
IO.puts Calliope.render(haml)
@topherhunt
topherhunt / git-log-hoc.rb
Last active February 2, 2017 03:33
Display counts of changed files and inserted / deleted lines in Git log
# Parse and condense `git log` output to include the hash, date, author, message,
# and change statistics all on one line. Run the script with the following command
# (ie. alias this to `gl` or something short):
# git log --pretty=format:"%h %ai (%an) | %s" --shortstat | ruby ~/path/to/git-log-hoc.rb | less -RS
#
# Sample output (real output is colorized so you can tell the stat numbers apart):
# df79691 2016-11-18 (Topher Hunt) | Add Category and its assoc. to Video [14 111 21]
# 4f2bf68 2016-11-04 (Topher Hunt) | Video actions scoped to logged-in user [3 27 15]
# d6d0ee6 2016-11-04 (Topher Hunt) | Reorganize & refactor auth for Videos [8 64 32]
# 5733dc3 2016-11-03 (Topher Hunt) | Authenticate current user [3 36]