今天看了一个视频,“Ecto without db”。介绍了几种 adapter,可见 Ecto 是十分灵活的。这里就用 ETS 来演示。
mix new ecto_demo
cd ecto_demo
def application do
[
extra_applications: [:logger, :ets_ecto]
]
end
defp deps do
[
{:ets_ecto, "~> 0.0.1", github: "wojtekmach/ets_ecto"}
]
end
mix deps.get
mix compile
iex -S mix
# 1. Define `Repo`
defmodule Repo do
use Ecto.Repo,
otp_app: :my_app,
adapter: ETS.Ecto
end
# 2. Configure the application
Application.put_env(:my_app, Repo, [])
# 3. Start the Repo process. In a real project you'd put the Repo module in your project's supervision tree:
{:ok, _pid} = Repo.start_link()
# 4. Import Ecto.Query
import Ecto.Query
# 5. Define schema
defmodule Article do
use Ecto.Schema
schema "articles" do
field :title, :string
end
end
# 6. Interact with the Repo
Repo.insert!(%Article{title: "Article 1"})
q = from(a in Article, select: a.title)
Repo.all(q)
# => ["Article 1"]
# 7 changeset
import Ecto.Changeset
%Article{title: "Article 1", id: 52} |> cast(%{title: "article 1"}, [:title]) |> validate_required(:title) |> Repo.insert
%Article{title: "Article 1", id: 52} |> cast(%{title: "new 2"}, [:title]) |> validate_required(:title) |> Repo.update
就这样,好理解吗?不难吧。