Skip to content

Instantly share code, notes, and snippets.

@videlalvaro
Created April 27, 2015 14:24
Show Gist options
  • Save videlalvaro/e38b990126b0abdae2d5 to your computer and use it in GitHub Desktop.
Save videlalvaro/e38b990126b0abdae2d5 to your computer and use it in GitHub Desktop.
blog post example
%% compile and run fold_example:test().
%% Records used here were taken from RabbitMQ's source code.
-module(fold_example).
-compile(export_all).
-record('P_basic',
{content_type,
content_encoding,
headers,
delivery_mode,
priority,
correlation_id,
reply_to,
expiration,
message_id,
timestamp,
type,
user_id,
app_id,
cluster_id}).
-record(content,
{class_id,
properties,
properties_bin,
protocol,
payload_fragments_rev}).
-record(basic_message,
{exchange_name,
routing_keys = [],
content,
id,
is_persistent}).
-record(delivery,
{mandatory,
confirm,
sender,
message,
msg_seq_no,
flow}).
test() ->
H = [{h1, v1}, {h2, v2}, {h3, v3}],
R1 = #delivery{message = #basic_message{content = #content{properties = #'P_basic'{headers = H}}}},
R2 = #delivery{message = #basic_message{content = #content{}}},
R3 = #delivery{message = #basic_message{}},
R4 = #delivery{},
H = headers4(R1),
undefined = headers4(R2),
undefined = headers4(R3),
undefined = headers4(R4),
ok.
headers1(#delivery{message = #basic_message{content = #content{properties = #'P_basic'{headers = H}}}}) ->
H.
headers2(Delivery) ->
Msg = get_msg(Delivery),
Content = get_content(Msg),
Props = get_props(Content),
Headers = get_headers(Props),
Headers.
headers3(Delivery) ->
lists:foldl(fun (_, undefined) -> undefined;
(F, Acc) -> F(Acc)
end,
Delivery,
[fun get_msg/1, fun get_content/1,
fun get_props/1, fun get_headers/1]).
headers4(Delivery) ->
catch lists:foldl(fun (_, undefined) -> throw(undefined);
(F, Acc) -> F(Acc)
end,
Delivery,
[fun get_msg/1, fun get_content/1,
fun get_props/1, fun get_headers/1]).
get_msg(#delivery{message = Msg}) ->
Msg.
get_content(#basic_message{content = Content}) ->
Content.
get_props(#content{properties = Props}) ->
Props.
get_headers(#'P_basic'{headers = H}) ->
H.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment