Skip to content

Commit

Permalink
Add helper for working with Mandrill merge vars (#219)
Browse files Browse the repository at this point in the history
  • Loading branch information
jbernardo95 authored and paulcsmith committed Oct 7, 2016
1 parent 968da08 commit 67d6ac8
Show file tree
Hide file tree
Showing 2 changed files with 92 additions and 0 deletions.
53 changes: 53 additions & 0 deletions lib/bamboo/adapters/mandrill_helper.ex
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,59 @@ defmodule Bamboo.MandrillHelper do
email |> Email.put_private(:message_params, %{}) |> put_param(key, value)
end

@doc """
Set merge_vars that are used by Mandrill
## Example
email
|> put_merge_vars(users, fn(user) -> %{first_name: user.first_name} end)
A convenience function for:
email
|> put_param(email, "merge_vars", [
%{
rcpt: "user1@example.com",
vars: [
%{
"name": "full_name",
"content": "User 1"
}
]
},
%{
rcpt: "user2@example.com",
vars: [
%{
"name": "full_name",
"content": "User 2"
}
]
}
])
"""
def put_merge_vars(email, enumerable, fun) do
merge_vars = Enum.map(enumerable, fn(e) ->
%{
rcpt: e.email,
vars: merge_vars(e, fun)
}
end)

email |> put_param("merge_vars", merge_vars)
end

defp merge_vars(e, fun) do
fun.(e)
|> Enum.map(fn({ key, value }) ->
%{
"name": to_string(key),
"content": value
}
end)
end

@doc """
Set a single tag or multiple tags for an email.
Expand Down
39 changes: 39 additions & 0 deletions test/lib/bamboo/adapters/mandrill_helper_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,45 @@ defmodule Bamboo.MandrillHelperTest do
assert email.private.message_params == %{"track_links" => true}
end

test "put_merge_vars/3 puts a list of merge_vars in private.merge_vars" do
users = [
%{
email: "user1@example.com",
full_name: "User 1"
},
%{
email: "user2@example.com",
full_name: "User 2"
}
]

email = MandrillHelper.put_merge_vars new_email, users, fn(user) ->
%{full_name: user.full_name}
end

assert email.private.message_params == %{"merge_vars" => [
%{
rcpt: "user1@example.com",
vars: [
%{
"name": "full_name",
"content": "User 1"
}
]
},
%{
rcpt: "user2@example.com",
vars: [
%{
"name": "full_name",
"content": "User 2"
}
]
}
]
}
end

test "adds tags to mandrill emails" do
email = new_email |> MandrillHelper.tag("welcome-email")
assert email.private.message_params == %{"tags" => ["welcome-email"]}
Expand Down

0 comments on commit 67d6ac8

Please sign in to comment.