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 22%% @doc Formatter that understands records. 23%% 24%% Usage: 25%% 26%% 1> M = mochifmt_records:new([{rec, record_info(fields, rec)}]), 27%% M:format("{0.bar}", [#rec{bar=foo}]). 28%% foo 29 30-module(mochifmt_records). 31-author('bob@mochimedia.com'). 32-export([new/1, get_value/3]). 33 34new([{_Rec, RecFields}]=Recs) when is_list(RecFields) -> 35 {?MODULE, Recs}. 36 37get_value(Key, Rec, {?MODULE, Recs}) 38 when is_tuple(Rec) and is_atom(element(1, Rec)) -> 39 try begin 40 Atom = list_to_existing_atom(Key), 41 {_, Fields} = proplists:lookup(element(1, Rec), Recs), 42 element(get_rec_index(Atom, Fields, 2), Rec) 43 end 44 catch error:_ -> mochifmt:get_value(Key, Rec) 45 end; 46get_value(Key, Args, {?MODULE, _Recs}) -> 47 mochifmt:get_value(Key, Args). 48 49get_rec_index(Atom, [Atom | _], Index) -> 50 Index; 51get_rec_index(Atom, [_ | Rest], Index) -> 52 get_rec_index(Atom, Rest, 1 + Index). 53 54 55%% 56%% Tests 57%% 58-ifdef(TEST). 59-include_lib("eunit/include/eunit.hrl"). 60-endif. 61