Rack::Affiliates is a rack middleware that extracts information about the referrals came from an affiliated site. Specifically, it looks up for referer url and compare it with the database in the request. If found, it persists referring url and time in a cookie for later use.
Affiliate links tracking is very common task if you want to promote your online business. This middleware helps you to do that.
- You associate an affiliate tag (for eg.
ABC123
) with your partner. - The affiliate promotes your business at http://partner.org by linking to your site with like
http://yoursite.org?ref=ABC123
. - A user clicks through the link and lands on your site.
- Rack::Affiliates middleware finds
ref
parameter in the request, extracts affiliate tag and saves it in a cookie - User signs up (now or later) and you mark it as a referral from your partner
- PROFIT!
Piece a cake:
gem install rack-affiliates
Add the middleware to your application stack:
# Rails 3 App - in config/application.rb
class Application < Rails::Application
...
config.middleware.use Rack::Affiliates
...
end
# Rails 2 App - in config/environment.rb
Rails::Initializer.run do |config|
...
config.middleware.use "Rack::Affiliates"
...
end
Now you can check any request to see who came to your site via an affiliated link and use this information in your application. Affiliate tag is saved in the cookie and will come into play if user returns to your site later.
class ExampleController < ApplicationController
def index
str = if request.env['affiliate.tag'] && affiliate = User.find_by_affiliate_tag(request.env['affiliate.tag'])
"Halo, referral! You've been referred here by #{affiliate.name} from #{request.env['affiliate.from']} @ #{Time.at(env['affiliate.time'])}"
else
"We're glad you found us on your own!"
end
render :text => str
end
end
You can customize parameter name by providing :param
option (default is ref
).
By default cookie is set for 30 days, you can extend time to live with :ttl
option (default is 30 days).
#Rails 3 in config/application.rb
class Application < Rails::Application
...
config.middleware.use Rack::Affiliates, {:param => 'aff_id', :ttl => 3.months}
...
end
The :domain
option allows to customize cookie domain.
#Rails 3 in config/application.rb
class Application < Rails::Application
...
config.middleware.use Rack::Affiliates, :domain => '.example.org'
...
end
Middleware will set cookie on .example.org
so it's accessible on www.example.org
, app.example.org
etc.
The :overwrite
option allows to set whether to overwrite the existing affiliate tag previously stored in cookies. By default it is set to true
.
Thanks goes to Rack::Referrals (https://github.com/deviantech/rack-referrals) for the inspiration.