Class: Rack::Affiliates

Inherits:
Object
  • Object
show all
Defined in:
lib/rack-affiliates.rb

Overview

Rack Middleware for extracting information from the request params and cookies. It populates env, # env and +env if it detects a request came from an affiliated link

Constant Summary collapse

"aff_tag"
"aff_from"
"aff_time"
"aff_extra"

Instance Method Summary collapse

Constructor Details

#initialize(app, opts = {}) ⇒ Affiliates

Returns a new instance of Affiliates.



13
14
15
16
17
18
19
20
21
# File 'lib/rack-affiliates.rb', line 13

def initialize(app, opts = {})
  @app = app
  @param = opts[:param] || "ref"
  @cookie_ttl = opts[:ttl] || 60*60*24*30  # 30 days
  @cookie_domain = opts[:domain] || nil
  @allow_overwrite = opts[:overwrite].nil? ? true : opts[:overwrite]
  @cookie_path = opts[:path] || nil
  @extras = opts[:extra_params] || []
end

Instance Method Details

#affiliate_info(req) ⇒ Object



59
60
61
# File 'lib/rack-affiliates.rb', line 59

def affiliate_info(req)
  params_info(req) || cookie_info(req)
end

#call(env) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/rack-affiliates.rb', line 23

def call(env)
  req = Rack::Request.new(env)

  params_tag = req.params[@param]
  cookie_tag = req.cookies[COOKIE_TAG]

  if cookie_tag
    tag, from, time, extras = cookie_info(req)
  end

  if params_tag && params_tag != cookie_tag
    if tag
      if @allow_overwrite
        tag, from, time, extras = params_info(req)
      end
    else
      tag, from, time, extras = params_info(req)
    end
  end

  if tag
    env["affiliate.tag"] = tag
    env['affiliate.from'] = from
    env['affiliate.time'] = time
    env['affiliate.extras'] = extras
  end

  status, headers, body = @app.call(env)

  if tag != cookie_tag
    bake_cookies(headers, tag, from, time, extras)
  end

  [status, headers, body]
end


70
71
72
73
74
# File 'lib/rack-affiliates.rb', line 70

def cookie_info(req)
  extras = {}
  @extras.each { |key| extras[key] = req.cookies["#{COOKIE_EXTRA_VARS}.#{key}"] }
  [req.cookies[COOKIE_TAG], req.cookies[COOKIE_FROM], req.cookies[COOKIE_TIME].to_i, extras]
end

#params_info(req) ⇒ Object



63
64
65
66
67
68
# File 'lib/rack-affiliates.rb', line 63

def params_info(req)
  extras = {}
  @extras.each { |key| extras[key] = req.params[key.to_s] }

  [req.params[@param], req.env["HTTP_REFERER"], Time.now.to_i, extras]
end