Created
March 7, 2019 14:45
-
-
Save bnadlerjr/4cf1cebd42147ec2044585804650d5bc to your computer and use it in GitHub Desktop.
Alternative refactor for https://avdi.codes/service-objects/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class DbGateway | |
def add_ipn(email, params) | |
DB[:ipns].insert(email_address: email, data: Sequel.pg_json(params) | |
end | |
def generate_redemption_token(email) | |
SecureRandom.hex.tap do |t| | |
DB[:tokens].insert(email_address: email, value: t) | |
end | |
end | |
end | |
class MailService | |
def send_claim_purchase_email(email, token) | |
subject = "Claim your purchase!" | |
redemption_url_template = | |
Addressable::Template.new("#{request.base_url}/redeem?token={token}") | |
email_template = Tilt.new("templates/welcome_email.txt.erb") | |
contact_email = "[email protected]" | |
redemption_url = redemption_url_template.expand("token" => token) | |
body = email_template.render(Object.new, | |
login_url: redemption_url, | |
contact_email: contact_email) | |
# Send the email | |
Pony.mail(to: email, | |
from: contact_email, | |
subject: subject, | |
body: body, | |
via: :smtp, | |
via_options: settings.email_options) | |
end | |
end | |
end | |
####### | |
set :db, DbGateway.new | |
set :mail_service, MailService.new | |
post "/ipn" do | |
demand_basic_auth | |
email = params.fetch("payer_email") { "<MISSING_EMAIL>" } | |
settings.db.add_ipn(email, params) | |
token = settings.db.generate_redemption_token(email) | |
settings.mail_service.send_claim_purchase_email(email, token) | |
[202, "Accepted"] | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment