Skip to content

Commit

Permalink
Make emails serializable (#92)
Browse files Browse the repository at this point in the history
* Make emails serializable

Fixes <#91>.

* Ensure that an attachment cannot be added more than once to the same email

* Add back `attachments` argument to `.def_equals` call
  • Loading branch information
akadusei authored Feb 25, 2024
1 parent ea5e7e2 commit 55d2838
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 5 deletions.
19 changes: 19 additions & 0 deletions spec/email_spec.cr
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
require "json"
require "./spec_helper"

private class User
Expand Down Expand Up @@ -84,6 +85,17 @@ private class UndeliverableEmail < Carbon::Email
to Carbon::Address.new("[email protected]")
end

private class SerializableEmail < BareMinimumEmail
include JSON::Serializable

MEMORY = IO::Memory.new

attachment({io: MEMORY, file_name: "file.txt", mime_type: "text/plain"})

# This is to check that an attachment cannot be added more than once
attachment({file_name: "file.txt", mime_type: "text/plain", io: MEMORY})
end

describe Carbon::Email do
it "can build a bare minimum email" do
email = BareMinimumEmail.new
Expand Down Expand Up @@ -153,6 +165,13 @@ describe Carbon::Email do
email.html_body.should contain "Email body"
end

it "can be serialized" do
email = SerializableEmail.from_json("{}")

email.attachments.size.should eq(1)
email.attachments.first[:io]?.should eq(SerializableEmail::MEMORY)
end

context "deliverable?" do
it "is not delivery it is digiorno" do
email = UndeliverableEmail.new
Expand Down
12 changes: 7 additions & 5 deletions src/carbon/email.cr
Original file line number Diff line number Diff line change
Expand Up @@ -91,15 +91,17 @@ abstract class Carbon::Email
end
end

@attachments = [] of Carbon::Attachment
getter attachments
def attachments
[] of Carbon::Attachment
end

macro attachment(value)
def attachments : Array(Carbon::Attachment)
{% if @type.methods.map(&.name).includes?("attachments".id) %}
previous_def
{% if @type.methods.map(&.name).includes?(:attachments.id) %}
previous_def | [{{ value }}]
{% else %}
super | [{{ value }}]
{% end %}
@attachments << {{value}}
end
end

Expand Down

0 comments on commit 55d2838

Please sign in to comment.