Created
May 11, 2016 11:44
-
-
Save ijunaid8989/d0a29152ba1e38453ee072db8e71db93 to your computer and use it in GitHub Desktop.
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
Short but not appreciated enough | |
defp validate_params(params) do | |
cond do | |
!validate?(params["frequency"]) -> | |
{:invalid, "The parameter 'frequency' isn't valid."} | |
!validate?(params["storage_duration"]) -> | |
{:invalid, "The parameter 'storage_duration' isn't valid."} | |
!cr_status?(params["status"]) -> | |
{:invalid, "The parameter 'status' isn't valid."} | |
true -> | |
{:ok} | |
end | |
end | |
def validate?(nil), do: false | |
def validate?(integer) when is_integer(integer), do: true | |
def validate?(integer) do | |
case Integer.parse(integer) do | |
{_number, ""} -> true | |
_ -> false | |
end | |
end | |
def cr_status?(""), do: false | |
def cr_status?(nil), do: false | |
def cr_status?("off"), do: true | |
def cr_status?("on"), do: true | |
def cr_status?("on-scheduled"), do: true | |
def cr_status?(status), do: false | |
Long but appreciated | |
defp validate_params(params) do | |
with :ok <- validate?("frequency", params["frequency"]), | |
:ok <- validate?("storage_duration", params["storage_duration"]), | |
:ok <- validate?("status", params["status"]), | |
do: :ok | |
end | |
def validate?("status", "on"), do: :ok | |
def validate?("status", "off"), do: :ok | |
def validate?("status", "on-scheduled"), do: :ok | |
def validate?("status" = key, _invalid), do: invalid(key) | |
def validate?(key, value) when is_integer(value), do: :ok | |
def validate?(key, value) when value in [nil, ""], do: invalid(key) | |
def validate?(key, value) when is_bitstring(value), do: validate?(key, to_integer(value)) | |
def validate?(key, _invalid), do: invalid(key) | |
defp invalid(key), do: {:invalid, "The parameter '#{key}' isn't valid."} | |
defp to_integer(value) do | |
case Integer.parse(value) do | |
{number, _} -> number | |
_ -> :error | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment