Class: Rack::MultiTenant::GetCurrentTenant

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

Defined Under Namespace

Classes: Builder

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, foo = nil, &getter) ⇒ GetCurrentTenant

Returns a new instance of GetCurrentTenant.



51
52
53
# File 'lib/rack/multitenant/get_current_tenant.rb', line 51

def initialize(app, foo = nil, &getter)
  @app, @getter = app, foo || getter
end

Class Method Details

.buildObject

Convenience method for initializing the GetCurrentTenant middleware with a stack of strategies.

>> GetCurrentTenant = Rack::MultiTenant::GetCurrentTenant

A custom getter that will be instantiated once and called.

>> class MyCustomGetter
>>   def initialize(host)
>>     @host = host
>>   end
>>   def call(req)
>>     req.host == @host ? :custom : nil
>>   end
>> end

>> # Stub the rest of the Rack stack to return the env value we're
>> # interested in.
>> next_app = lambda {|env| env["rack.multitenant.current_tenant"]}

>> # Build the middleware and instantiate it.
>> app = GetCurrentTenant.new(next_app, GetCurrentTenant.build do |get|
>>   get.use :Subdomain, "example.com", &:to_sym
>>   get.use MyCustomGetter, "custom"
>>   get.use lambda {|req| req.host == "lambda" ? :lambda : nil }
>>   get.use :Default, :default_tenant
>> end[1])

>> subdomain_req_env = {"HTTP_HOST" => "foo.example.com"}
>> app.call(subdomain_req_env)
=> :foo

>> custom_req_env = {"HTTP_HOST" => "custom"}
>> app.call(custom_req_env)
=> :custom

>> lambda_req_env = {"HTTP_HOST" => "lambda"}
>> app.call(lambda_req_env)
=> :lambda

>> default_req_env = {"HTTP_HOST" => "kwjibo"}
>> app.call(default_req_env)
=> :default_tenant


47
48
49
# File 'lib/rack/multitenant/get_current_tenant.rb', line 47

def self.build
  [self, (Builder.new.tap {|b| yield b}).to_proc]
end

Instance Method Details

#call(env) ⇒ Object



55
56
57
58
59
60
# File 'lib/rack/multitenant/get_current_tenant.rb', line 55

def call(env)
  if tenant = @getter.call(Rack::Request.new(env))
    env["rack.multitenant.current_tenant"] = tenant
  end
  @app.call(env)
end