PageRenderTime 48ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/src/mochifmt_records.erl

http://github.com/basho/mochiweb
Erlang | 60 lines | 23 code | 7 blank | 30 comment | 0 complexity | 6bc16b7fb95ea7246fee362f534b8748 MD5 | raw file
Possible License(s): MIT
  1. %% @author Bob Ippolito <bob@mochimedia.com>
  2. %% @copyright 2008 Mochi Media, Inc.
  3. %%
  4. %% Permission is hereby granted, free of charge, to any person obtaining a
  5. %% copy of this software and associated documentation files (the "Software"),
  6. %% to deal in the Software without restriction, including without limitation
  7. %% the rights to use, copy, modify, merge, publish, distribute, sublicense,
  8. %% and/or sell copies of the Software, and to permit persons to whom the
  9. %% Software is furnished to do so, subject to the following conditions:
  10. %%
  11. %% The above copyright notice and this permission notice shall be included in
  12. %% all copies or substantial portions of the Software.
  13. %%
  14. %% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. %% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. %% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  17. %% THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. %% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. %% FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  20. %% DEALINGS IN THE SOFTWARE.
  21. %% @doc Formatter that understands records.
  22. %%
  23. %% Usage:
  24. %%
  25. %% 1> M = mochifmt_records:new([{rec, record_info(fields, rec)}]),
  26. %% M:format("{0.bar}", [#rec{bar=foo}]).
  27. %% foo
  28. -module(mochifmt_records).
  29. -author('bob@mochimedia.com').
  30. -export([new/1, get_value/3]).
  31. new([{_Rec, RecFields}]=Recs) when is_list(RecFields) ->
  32. {?MODULE, Recs}.
  33. get_value(Key, Rec, {?MODULE, Recs})
  34. when is_tuple(Rec) and is_atom(element(1, Rec)) ->
  35. try begin
  36. Atom = list_to_existing_atom(Key),
  37. {_, Fields} = proplists:lookup(element(1, Rec), Recs),
  38. element(get_rec_index(Atom, Fields, 2), Rec)
  39. end
  40. catch error:_ -> mochifmt:get_value(Key, Rec)
  41. end;
  42. get_value(Key, Args, {?MODULE, _Recs}) ->
  43. mochifmt:get_value(Key, Args).
  44. get_rec_index(Atom, [Atom | _], Index) ->
  45. Index;
  46. get_rec_index(Atom, [_ | Rest], Index) ->
  47. get_rec_index(Atom, Rest, 1 + Index).
  48. %%
  49. %% Tests
  50. %%
  51. -ifdef(TEST).
  52. -include_lib("eunit/include/eunit.hrl").
  53. -endif.