Skip to content

Commit

Permalink
Code for step 2
Browse files Browse the repository at this point in the history
  • Loading branch information
akoutmos committed Jun 1, 2020
1 parent 95e5e60 commit 56e57e5
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 11 deletions.
31 changes: 20 additions & 11 deletions lib/store_inventory.ex
Original file line number Diff line number Diff line change
@@ -1,18 +1,27 @@
defmodule StoreInventory do
@moduledoc """
Documentation for `StoreInventory`.
"""
alias StoreInventory.Item

@doc """
Hello world.
@repo Application.get_env(:store_inventory, :repo)

## Examples
def insert_item(params) do
%Item{}
|> Item.changeset(params)
|> @repo.insert()
end

def all_items do
@repo.all(Item)
end

iex> StoreInventory.hello()
:world
def average_item_price do
{total, num_items} =
all_items()
|> Enum.reduce({0, 0}, fn %Item{} = item, {sum, count} ->
{sum + item.price, count + 1}
end)

"""
def hello do
:world
if num_items == 0,
do: 0,
else: total / num_items
end
end
26 changes: 26 additions & 0 deletions lib/store_inventory/item.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
defmodule StoreInventory.Item do
use Ecto.Schema

import Ecto.Changeset

alias __MODULE__

@all_fields [:name, :description, :price, :quantity]

schema "items" do
field(:name, :string)
field(:description, :string)
field(:price, :decimal)
field(:quantity, :integer)

timestamps()
end

def changeset(%Item{} = item, params \\ %{}) do
item
|> cast(params, @all_fields)
|> validate_required(@all_fields)
|> validate_number(:quantity, greater_than: 0)
|> validate_number(:price, greater_than: 0)
end
end
14 changes: 14 additions & 0 deletions priv/repo/migrations/20200601203937_items.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
defmodule StoreInventory.Repo.Migrations.Items do
use Ecto.Migration

def change do
create table("items") do
add(:name, :string)
add(:description, :string)
add(:price, :decimal)
add(:quantity, :integer)

timestamps()
end
end
end

0 comments on commit 56e57e5

Please sign in to comment.