TIL, 2018-02-23, Mechanics/Koans
Musings
- Tried tinkering around accessing app config.
Application.get_env
is different in Phoenix than from Elixir.Application.get_env(:my, My.Endpoint)[:title]
Reference
- When you edit something in
config/config.exs
, the server asks you to restart. It’s not like that in Rails, which causes “???” confusion. - Pattern matching: Reference Reference Reference
- Underscore if you don’t care about a part.
- You can’t have a function on the left side.
- alias multiple:
alias Teacher.{Repo, Post}
iex> x = 1
iex> ^x = 2 to attempt a match instead of a reassignment? # Pin operator
iex> { x, x } = { 1, 1 }
iex> { x, x } = { 1, 2 } # All references should bind to the same pattern.
# Match on starts_with
def greet("Ben" <> _) do
IO.puts("Hello, Ben")
end
# Lists
def greet(["Ben" <> _, _last_name]) do
IO.puts("Hello, Ben")
end
# Head/Tail
def greet([name | _]) do
IO.puts("Hello, #{name}")
end
# Tuples
def greet({"Ben" <> _, _last_name}) do
IO.puts("Hello, Ben")
end
# Maps. As long has map has k/v, this will work
def greet(%{first_name: name}) do
IO.puts("Hello, #{name}")
end
Elixir Koans, 1-6.
"hello" <> "world"
to concatenate.String.contains?("Hello", "He")
,trim
,duplicate
,upcase
,reverse
.Integer.digits/1
: splits to list.Integer.to_string
Integer.parse("5 years") == {5, " years"}
# the un-parseable part is also returned.Integer.parse("1.2") == {1, ".2"}
# note first return in tuple is int, second is stringFloat.ceil\2
# second argument decimal places to roundFloat.floor
Range.new(1, 10)
Range.range?(1..10)
# truetrue
,false
, andnil
are atoms.:true
==true
- Tuple:
tuple_size
,elem
,insert_at
,append
,delete_at
,to_list
. - List:
[a] ++ [b], [a, b] -- [a]
,List.wrap("value") => ["value"]
.
ElixirCasts, Guards
- Guards: does a type check on the function argument (not all expressions are allowed, and it’s this way because they don’t want anything bad to happens while executing guards/no mutations happen anywhere).
iex> r(Shirt)
to reload in memory.
def greet(name) when is_binary(name) do
IO.puts("Hello, #{name}")
end
---
defmodule SizeTranslator do
defguard is_small(size) when size == 1 or size == "s" or size == "S"
end
defmodule Shirt do
import SizeTranslator
def colors_for(size) when is_small(size) do
# Colors for small size
end
end
ElixirCasts, Gravatar with Phoenix
def gravatar(email)
email
|> String.trim()
|> String.downcase()
|> :erlang.md5() # Use erlang in Elixir
|> Base.encode16(case: :lower)
img = "https://www.gravatar.com/avatar/#{hash}?s=150&d=identicon"
img_tag(img)
end