Skip to content

Instantly share code, notes, and snippets.

@caike
Last active July 5, 2021 15:57
Show Gist options
  • Save caike/4f3b3360a71af129a0917c4678c88240 to your computer and use it in GitHub Desktop.
Save caike/4f3b3360a71af129a0917c4678c88240 to your computer and use it in GitHub Desktop.
snippets para o blog post sobre mix task
defmodule GuitarStore.Repo.Migrations.AddIsCustomShopToGuitars do
use Ecto.Migration
def change do
alter table("guitars") do
add :is_custom_shop, :boolean, default: false
end
create index("guitars", ["is_custom_shop"])
end
end
defmodule Mix.Tasks.PopulateIsCustomShop do
@shortdoc "Populates is_custom_shop column"
use Mix.Task
import Ecto.Query
alias GuitarStore.Inventory.Guitar
alias GuitarStore.{Repo, Utils}
@requirements ["app.start"]
def run(_) do
Enum.map(Utils.custom_shop_entries(), &update_guitars/1)
end
defp update_guitars({make, model, year}) do
from(g in Guitar,
where: g.make == ^make and g.model == ^model and g.year == ^year,
select: g
)
|> Repo.update_all(set: [is_custom_shop: true])
end
end
defmodule Mix.Tasks.PopulateIsCustomShopTest do
use GuitarStore.DataCase
alias Mix.Tasks.PopulateIsCustomShop
alias GuitarStore.Utils
alias GuitarStore.Inventory
@custom_shop_entries Utils.custom_shop_entries()
test "populates custom shop field" do
# Create 1 custom shop with flag false
[{make, model, year} | _] = @custom_shop_entries
{:ok, custom} =
Inventory.create_guitar(%{
make: make,
model: model,
year: year
})
# Create 1 non-custom shop with flag false
{:ok, non_custom} =
Inventory.create_guitar(%{
make: "#{make}-non-custom",
model: model,
year: year
})
refute custom.is_custom_shop
refute non_custom.is_custom_shop
# Run task
PopulateIsCustomShop.run([])
# custom shop should have flag true
custom = Inventory.get_guitar!(custom.id)
assert custom.is_custom_shop
# non-custom shop should have flag false
non_custom = Inventory.get_guitar!(non_custom.id)
refute non_custom.is_custom_shop
end
end
defmodule GuitarStore.Utils do
def custom_shop_entries() do
[
{"Gibson", "SG", 1999},
{"Fender", "Telecaster", 2020}
]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment