Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make emails serializable #92

Merged
merged 3 commits into from
Feb 25, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
14 changes: 8 additions & 6 deletions src/carbon/email.cr
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ abstract class Carbon::Email
abstract def from : Carbon::Address
abstract def to : Array(Carbon::Address)

def_equals subject, from, to, cc, bcc, headers, text_body, html_body, attachments
def_equals subject, from, to, cc, bcc, headers, text_body, html_body

# Set this value to `false` to prevent the email from
# being delivered
Expand Down 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
Loading