Class: Rack::Redir

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

Overview

Bounce those annoying favicon.ico requests

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Redir

Returns a new instance of Redir.



6
7
8
# File 'lib/rack/redir.rb', line 6

def initialize(app)
  @app = app
end

Instance Method Details

#append_parameter_separater(url) ⇒ Object



43
44
45
# File 'lib/rack/redir.rb', line 43

def append_parameter_separater url
  url.match('\?') ? "#{url}&" : "#{url}?"
end

#call(env) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/rack/redir.rb', line 10

def call(env)
  env['PATH_INFO'] =~ %r{^a/(.+)$}
  parsed_path = env['PATH_INFO'].split(/\//)
  if "#{parsed_path.second}/" == Redirect.path
    redir_asset = parsed_path.last 
    redirect_record = (Redirect.where shortened_id: redir_asset).to_a.last
    headers = env.select {|k,v| k.start_with? 'HTTP_'}
    if redirect_record and redirect_record.shortened_id == redir_asset
      redirect_url = redirect_record.original_url.strip 
      redirect_to_url = redirect_url.start_with?('http') ? redirect_url : "http://#{redirect_url}"
      redirect_log = RedirectLog.new(:redirect_id => redirect_record.id, 
                                     :headers => headers, :request_time => Time.now)
      redirect_log.save!
      if Redirect.append_tracking_info
        redirect_to_url = append_parameter_separater redirect_to_url
        redirect_to_url = "#{redirect_to_url}redirect_mongo_id=" +
                          "#{redirect_log.redirect_id}&redirect_log_mongo_id=#{redirect_log._id}"
      end
      if Redirect.append_google_analytics
        redirect_to_url = append_parameter_separater redirect_to_url 
        redirect_to_url = "#{redirect_to_url}utm_source=#{Rack::Utils.escape Redirect.host}" +
                          "&utm_campaign=#{redirect_log.redirect_id}__#{redirect_log._id}"
      end  
      [302, {'Location' => redirect_to_url}, self]
    else
      [404, {}, self]
    end
  else
    @app.call env
  end

end

#each(&block) ⇒ Object



47
48
# File 'lib/rack/redir.rb', line 47

def each(&block)
end