Skip to content

Instantly share code, notes, and snippets.

@ferd
Created August 14, 2013 18:43
Show Gist options
  • Select an option

  • Save ferd/6234149 to your computer and use it in GitHub Desktop.

Select an option

Save ferd/6234149 to your computer and use it in GitHub Desktop.
-module(test).
-compile(export_all).
-record(request_status, {code, id, properties, message}).
main() ->
print(#request_status{code=232}),
print(#request_status{code=232, id= <<"ok">>, properties=[{a,b}], message= <<"hi">>}),
print(#request_status{code=232, id= <<"ok">>, properties=[{a,b}], message= "hi"}),
print(#request_status{code=232, id= <<"ok">>, properties="still a list, you fail", message= <<"hi">>}),
print(#request_status{code=232, id= {ok}, properties=[{a,b}], message= <<"hi">>}),
print(#request_status{code=232, id= {ok}, properties=[{a,b}], message= "hi"}).
print(Req) ->
try
io:format("~s~n",[[validate(X) || X <- convert(Req)]])
catch
error:{bad_type, {Prop, Term}} ->
io:format("bad value for ~p: ~p~n", [Prop,Term])
end.
convert(#request_status{code=C, id=I, properties=P, message=M}) ->
[{code,C}, {id,I}, {properties,P}, {message,M}].
validate({code, Code}) -> [" code=", Code];
validate({id, undefined}) -> "";
validate({message,undefined}) -> "";
validate({properties,undefined}) -> "";
validate({id, Id}) when is_binary(Id) -> [" id=", Id];
validate({message,M}) when is_binary(M) -> [" message=", M];
validate({properties,L}) when is_list(L) -> [" props=", io_lib:format("~p",[L])];
validate({Prop, Term}) -> error({bad_type, {Prop, Term}}).
@ferd

ferd commented Aug 14, 2013

Copy link
Copy Markdown
Author
6> test:main().
code=232
code=232 id=ok props=[{a,b}] message=hi
bad value for message: "hi"
code=232 id=ok props="still a list, you fail" message=hi
bad value for id: {ok}
bad value for id: {ok}
ok

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment