Skip to content
Permalink
Browse files
Code for step 2
  • Loading branch information
akoutmos committed Jun 1, 2020
1 parent 95e5e60 commit 56e57e524958543e0e873b194cf379c6a5dda37b
Showing 3 changed files with 60 additions and 11 deletions.
@@ -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
@@ -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
@@ -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.