I'm developing an Erlang system and having reoccurring problems with the fact that records are compile-time pre-processor macros (almost), and that they cant be manipulated at runtime…
basically, I'm working with a property pattern, where properties are added at run-time to objects on the front-end (AS3). Ideally, I would reflect this with a list on the Erlang side, since its a fundamental data type, but then using records in QCL [to query ETS tables] would not be possible since to use them I have to specifically say which record property I want to query over… I have at least 15 columns in the larges table, so listing them all in one huge switch statement (case X of) is just plain ugly.
does anyone have any ideas how to elegantly solve this? maybe some built-in functions for creating tuples with appropriate signatures for use in pattern matching (for QLC)?
thanks
Best Answer
It sounds like you want to be able to do something like
get_record_field(Field, SomeRecord)
whereField
is determined at runtime by user interface code say.You're right in that you can't do this in standard erlang as records and the
record_info
function are expanded and eliminated at compile time.There are a couple of solutions that I've used or looked at. My solution is as follows: (the example gives runtime access to the
#dns_rec
and#dns_rr
records frominet_dns.hrl
)A version of this that compiles is available here: rec_test.erl
You can also extend this dynamic field lookup to dynamic generation of matchspecs for use with
ets:select/2
ormnesia:select/2
as shown below:Ulf Wiger has also written a parse_transform, Exprecs, that more or less does this for you automagically. I've never tried it, but Ulf's code is usually very good.