I'm currently learning to code Erlang. I have a web application on top of Chicago Boss. I have a model called Todo, and I would like to offer CRUD operations on it as a REST API.
In my PUT method I have this code:
index('PUT', [Id]) ->
Todo = boss_db:find(Id),
Body = element(2, mochijson:decode(Req:request_body())),
%% Set the new values
NewTodo = Todo:attributes([
{subject, proplists:get_value("subject", Body)},
{done, proplists:get_value("done", Body)}
])
,
{json, [{todo, element(2, NewTodo:save())}]}.
How can I optimize this code fragment? Or is this already the best possible?
Is there some "smarter" way to change the keys of a proplist to atom keys? Like this:
[{"subject", "Foo"}] -> [{subject, "Foo"}].
I also find it kind of tedious to assign a Todo variable and then have a NewTodo. Sadly I can't find some good example Erlang Chicago Boss apps on github that I can check out.
You always can do something like this:
But I doubt, it will be significant speed improvement in your case.
May be you will be able squeeze last bit from this:
Which is worth only for benchmark code competitions ;-) (Note there is not
lists:reverse/1
call in last clause. It would be ruining improvement form previous version.)P.S.: If you think I'm micro-optimization freak, you are right, so I would replace
lists:reverse/1
call withlists:reverse/2
to use BIF directly and save some more time ;-)