Skip to content

Instantly share code, notes, and snippets.

View jordangraft's full-sized avatar

Jordan Graft jordangraft

View GitHub Profile
@jordangraft
jordangraft / application_controller.rb
Last active April 24, 2016 19:27
Controller action for receiving a ga_id from the client side
class ApplicationController < ActionController::Base
##
# Set the Google Analytics CID as passed via query params
# and then saved onto an order if they convert
def set_ga_id
session[:ga_id] ||= params[:ga_id]
render nothing: true
end
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-54124351-6', 'auto');
ga(function(tracker) {
clientId = tracker.get('clientId');
$.post({
def create
@order = Order.new(order_params)
@order.ga_id = session[:ga_id]
if @order.save
redirect_to orders_edit_path, notice: 'Order was successfully created.'
else
render 'static/home'
end
end
#app/workers/analytics_worker.rb
##
# A Sidekiq worker that handles sending order data to Analytics
# Measurement Protocol
class AnalyticsWorker
include Sidekiq::Worker
sidekiq_options retry: 2
def perform(id)
{
"Version": "2008-10-17",
"Statement": [
{
"Sid": "GiveSESPermissionToWriteEmail",
"Effect": "Allow",
"Principal": {
"Service": [
"ses.amazonaws.com"
]
var AWS = require('aws-sdk');
var https = require('https');
exports.handler = function(event, context) {
var sesNotification = event.Records[0].ses;
var messageId = sesNotification.mail.messageId;
var receipt = sesNotification.receipt;
var from = sesNotification.mail.commonHeaders.from[0];
var appUrl = 'https://www.example.com'
config.before do
WebMock.disable_net_connect!(allow_localhost: true)
stub_request(:get, "https://my-email-bucket.s3.amazonaws.com/test")
.to_return(status: 200, body: File.read('spec/support/lambda_email'))
end
class Email < ActiveRecord::Base
def self.process_incoming_email(message_id)
obj = AWS::S3.new.buckets['my-email-bucket'].objects[message_id]
contents = obj.read
from = contents.match(/(?<=From: )(.*?)(?=\n)/).try(:to_s)
to = contents.match(/(?<=To: )(.*?)(?=\n)/).try(:to_s)
subject = contents.match(/(?<=Subject: )(.*?)(?=\n)/).try(:to_s)
body = contents.match(/(?<=Content-Type: text\/html; charset\=UTF-8)(.*?)(?=--)/m).try(:to_s)
self.create(
class EmailsController < ApplicationController
##
# Receive the AWS post, validate the token and pass to our model method
def incoming
if params[:token] && (params[:token] == 'test_token')
@email = Email.process_incoming_email(params[:message_id])
if @email.valid?
render text: 'email created', status: :created
else
rails g scaffold email from:string body:text to:string subject:string