Last active
August 29, 2015 14:15
-
-
Save joshdholtz/b465093c5a13a25bc7af to your computer and use it in GitHub Desktop.
Lazy Float
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
thing_1 = Project.Thing.create( %{ value: 3 } ) | |
thing_2 = Project.Thing.create( %{ value: "3.2" } ) | |
thing_3 = Project.Thing.create( %{ value: 3.2 } ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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