Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Elixir and Ecto

Elixir and Ecto

Patrick Van Stee

October 03, 2013
Tweet

More Decks by Patrick Van Stee

Other Decks in Technology

Transcript

  1. defmodule Hello do IO.puts "Before world defined" def world do

    IO.puts "Hello World" end IO.puts "After world defined" end Hello.world HELLO.EX
  2. # tuple { :a, :b, :c } # list [1,

    2, 3] [a: 1, b: 2, c: 3] # record defrecord User, name: "", age: nil User.new(name: "Patrick", age: 25) TYPE.EX
  3. # assignment a = 1 # => 1 # matching

    1 = a # => 1 2 = a # => ** (MatchError) ... { ^a, b } = { 1, 2 } # b => 2 [head | _] = [1, 2, 3] # head => 1 PATTERN.EX
  4. case { 1, 2, 3 } do { 4, 5,

    6 } -> "This won't match" { 1, x, 3 } when x > 0 -> "This will match and assign x" _ -> "No match" end GUARD.EX
  5. current_pid = self spawn fn -> current_pid <- :hello end

    receive do :hello -> IO.puts "Hello World" end PROCESS.EX
  6. defmodule Stacker.Supervisor do use Supervisor.Behaviour def start_link(stack) do :supervisor.start_link(__MODULE__, stack)

    end def init(stack) do children = [worker(Stacker.Server, [stack])] supervise children, strategy: :one_for_one end end SUPERVISOR.EX
  7. defmodule FindUser do import Ecto.Query def find_by_name(name) do query =

    from u in User, where: u.name == ^name, limit: 1 Repo.all(query) end end QUERY.EX
  8. defmodule Repo do use Ecto.Repo, adapter: Ecto.Adapters.Postgres def url do

    "ecto://user:pass@localhost/db" end end Repo.all(...) Repo.create(...) Repo.update(...) Repo.delete(...) REPO.EX
  9. defmodule User do use Ecto.Model queryable "user" do field :name,

    :string field :password, :string, default: "secret" has_many :projects, Project end end MODEL.EX
  10. def paginate(query, page, size) do extend query, limit: size, offset:

    (page - 1) * size end query = FindUser.find_by_state("GA") query |> paginate(1, 50) |> Repo.all PAGINATE.EX
  11. ?