Skip to content

Commit

Permalink
Add ByteWithUnit type
Browse files Browse the repository at this point in the history
  • Loading branch information
tlux committed May 30, 2019
1 parent 0819982 commit 651a5b6
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
49 changes: 49 additions & 0 deletions lib/file_size_ecto/type/byte_with_unit.ex
@@ -0,0 +1,49 @@
defmodule FileSizeEcto.Type.ByteWithUnit do
@behaviour Ecto.Type

alias FileSize.Convertible
alias FileSize.InvalidUnitError
alias FileSizeEcto.Type.Byte, as: ByteType

@impl true
def type, do: :map

@impl true
def cast(term)

def cast(%{"bytes" => _, "unit" => _} = term) do
load(term)
end

def cast(term) do
ByteType.cast(term)
end

@impl true
def dump(term) do
case cast(term) do
{:ok, size} ->
{:ok, %{
"bytes" => Convertible.normalized_value(size),
"unit" => to_string(size.unit)
}}

_ ->
:error
end
end

@impl true
def load(term)

def load(%{"bytes" => bytes, "unit" => unit_str})
when is_integer(bytes) and is_binary(unit_strs) do
unit = String.to_existing_atom(unit_str)
{:ok, FileSize.from_bytes(bytes, unit)}
rescue
error in [ArgumentError, InvalidUnitError] ->
:error
end

def load(_term), do: :error
end
1 change: 1 addition & 0 deletions test/support/test_schema.ex
Expand Up @@ -6,5 +6,6 @@ defmodule TestSchema do
embedded_schema do
field :bit_size, FileSizeEcto.Type.Bit
field :byte_size, FileSizeEcto.Type.Byte
field :byte_size_with_unit, FileSizeEcto.Type.ByteWithUnit
end
end

0 comments on commit 651a5b6

Please sign in to comment.