Search code examples
ruby-on-railsrubyapartment-gem

Request.host in initializer Rails 4


I am using the Apartment gem for a multi-tenant app and I'm using the "host_hash elevator" to switch the tenant based on the subdomain and host of the request.

This is done with the below code (from their documentation):

#initalizers/apartment.rb

# application.rb
module MyApplication
  class Application < Rails::Application
    config.middleware.use 'Apartment::Elevators::HostHash', {'example.com' => 'example_tenant'}
  end
end

Where it says 'example.com' => 'example_tenant' I need to send a hash with the request.host to find the company in my Company model where the value of the request_host database field matches request.host. If that makes sense?

if I hard code in an example so it's like the below code I can get it to work, but I don't know how to dynamically do it based on the request:

#initalizers/apartment.rb

# application.rb
module MyApplication
  class Application < Rails::Application
    config.middleware.use 'Apartment::Elevators::HostHash', {'test.lvh.me:3000' => 'test.lvh.me:3000'}
  end
end

The above code works because that's the domain that I'm currently on and it matches a field and apartment tenant that I had set up.

However, since this in an initializer when I put 'request.host' there I get an error: undefined local variable/method 'request'

If I use 'Rack::Request.new(env).host' I get undefined local variable/method 'env'

How can I get request.host in an an initializer to solve this problem?


Solution

  • thanks to some help I got on the apartment gem's github issues I was able to figure out a solution.

    #company.rb model
    def self.full_hosts_hash
        Company.all.inject(Hash.new) do |hash, company|
          hash[company.request_host] = company.request_host
          hash
        end
    end
    
    #apartment.rb initializer
    require 'apartment/elevators/host_hash'
    Rails.application.config.middleware.use 'Apartment::Elevators::HostHash', Company.full_hosts_hash