Skip to content

Instantly share code, notes, and snippets.

@bnadlerjr
Created March 7, 2019 14:45
Show Gist options
  • Save bnadlerjr/4cf1cebd42147ec2044585804650d5bc to your computer and use it in GitHub Desktop.
Save bnadlerjr/4cf1cebd42147ec2044585804650d5bc to your computer and use it in GitHub Desktop.
Alternative refactor for https://avdi.codes/service-objects/
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 = "contact@example.com"
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