Class: Rack::Redirect

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*redirects) ⇒ Redirect

Returns a new instance of Redirect.



62
63
64
65
66
# File 'lib/redirect.rb', line 62

def initialize(*redirects)
  @redirects = redirects.collect do |r|
    ::Redirect::Data.new(*r)
  end
end

Instance Attribute Details

#redirectsObject (readonly)

Returns the value of attribute redirects.



61
62
63
# File 'lib/redirect.rb', line 61

def redirects
  @redirects
end

Instance Method Details

#call(env) ⇒ Object



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/redirect.rb', line 68

def call(env)
  req = Request.new(env)
  if req.fullpath == '/sitemap.xml'
    return [200, {"Content-Type" => "text/xml"}, sitemap(req.host)]
  end
  if req.fullpath == '/' && index
    return [200, {"Content-Type" => "text/html"}, index]
  end      
  @redirects.each do |r|
    if req.fullpath.match(r.catch_url)
      redirect_url = r.redirect_url
      if $1
        redirect_url.gsub!('$1', $1)
      end
      puts "Match found for #{r.catch_url}."
      puts "Redirecting to #{redirect_url}"
      return [r.code, {"Location" => redirect_url, "Content-Type" => "text/html"}, "Redirecting to: #{redirect_url}"]
    end
  end
  [404, {"Content-Type" => "text/html"}, "not found"]
end

#indexObject



100
101
102
# File 'lib/redirect.rb', line 100

def index
  @index
end

#index=(index) ⇒ Object



104
105
106
# File 'lib/redirect.rb', line 104

def index= index
  @index = index
end

#sitemap(host) ⇒ Object



90
91
92
93
94
95
96
97
98
# File 'lib/redirect.rb', line 90

def sitemap(host)
  %(<?xml version="1.0" encoding="UTF-8"?>\n) +
  %(<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n) +
  @redirects.select{|r| r.name }.collect { |r|
    %(<url>\n) +
      %(<loc>http://#{host}#{r.redirect_url}</loc>\n) +
    %(</url>\n)}.join +
  %(</urlset>\n)
end