user502052
user502052

Reputation: 15257

How to initialize variables in a Rack statement?

I am using Ruby on Rails 3 and I am trying to use the Rack. Since I am not expert in this matter, I would like to know some thing about that.

The following code is from here.

require 'rack'

class Rack::ForceDomain
  def initialize(app, domain)
    @app = app
    @domain = domain
  end

  def call(env)
    request = Rack::Request.new(env)
    if @domain and request.host != @domain
      fake_request = Rack::Request.new(env.merge("HTTP_HOST" => @domain))
      Rack::Response.new([], 301, "Location" => fake_request.url).finish
    else
      @app.call(env)
    end
  end
end

Upvotes: 1

Views: 1390

Answers (1)

Michael Papile
Michael Papile

Reputation: 6856

Rack is a middleware to interface a higher level app (like rails) to a webserver (like mongrel). In rails, you can get this code to work by using:

# config.middleware.use "Rack::ForceDomain", "mydomain.com"

App is a reference to the Rails instance. Domain is added by the person you got that code from, it is not standard Rack initialize.

You do not need to go down to the rack level for what you are doing though for this. I personally prefer to do the rewrite through nginx, but you can do it in rails 3.

In your config/routes.rb file:

    constraints(:host => /example.com/) do
      root :to => redirect("http://www.example.com")
      match '/*path', :to => redirect {|params| "http://www.example.com/#{params[:path]}"}
    end

This is from http://railsdog.com/blog/2010/10/29/redirect-non-www-requests-the-rails3-way/

Upvotes: 2

Related Questions