Request.host 在初始值设定项中 Rails 4

Request.host in initializer Rails 4

我正在将公寓 gem 用于多租户应用程序,我正在使用 "host_hash elevator" 根据请求的子域和主机切换租户。

这是使用以下代码完成的(来自他们的文档):

#initalizers/apartment.rb

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

上面写着 'example.com' => 'example_tenant' 我需要发送一个带有 request.host 的散列来在我的公司模型中找到 [=42= 的值的公司] 数据库字段匹配 request.host。如果这有意义?

如果我在示例中硬编码,就像下面的代码一样,我可以让它工作,但我不知道如何根据请求动态地执行它:

#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

以上代码有效,因为这是我当前所在的域,它与我设置的田地和公寓租户相匹配。

但是,因为当我把 'request.host' 放在那里时,这是在初始化程序中,所以我得到一个错误:undefined local variable/method 'request'

如果我使用 'Rack::Request.new(env).host' 我得到 undefined local variable/method 'env'

如何在初始化程序中得到 request.host 来解决这个问题?

感谢一些帮助,我在公寓 gem 的 github 问题上找到了解决方案。

#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