Skip to content

Instantly share code, notes, and snippets.

@joshdholtz
Last active August 29, 2015 14:15
Show Gist options
  • Save joshdholtz/b465093c5a13a25bc7af to your computer and use it in GitHub Desktop.
Save joshdholtz/b465093c5a13a25bc7af to your computer and use it in GitHub Desktop.
Lazy Float
thing_1 = Project.Thing.create( %{ value: 3 } )
thing_2 = Project.Thing.create( %{ value: "3.2" } )
thing_3 = Project.Thing.create( %{ value: 3.2 } )
defmodule Project.LazyFloat do
def type, do: :float
def cast(string) when is_binary(string) do
case Float.parse(string) do
{float, _} -> {:ok, float}
:error -> :error
end
end
def cast(integer) when is_integer(integer) do
case Float.parse(to_string(integer)) do
{float, _} -> {:ok, float}
:error -> :error
end
end
def cast(_), do: :error
def blank?(_), do: false
def load(float) when is_float(float), do: {:ok, float}
def dump(float) when is_float(float), do: {:ok, float}
def dump(_), do: :error
end
defmodule Project.Thing do
use Project.Model
schema "things" do
field :value, Project.LazyFloat
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment