cirandas.net

ref: master

lib/noosfero/multi_tenancy.rb


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
module Noosfero
  class MultiTenancy

    def self.mapping
      @mapping ||= self.load_map
    end

    def self.on?
      !self.mapping.blank? || self.is_hosted_environment?
    end

    def self.db_by_host=(host)
      if host != @db_by_host
        @db_by_host = host
        ActiveRecord::Base.connection.schema_search_path = self.mapping[host]
      end
    end

    def self.setup!(host)
      return unless Noosfero::MultiTenancy.on?
      Noosfero::MultiTenancy.db_by_host = host
    end

    class Middleware
      def initialize(app)
        @app = app
      end

      def call(env)
        request = Rack::Request.new(env)
        Noosfero::MultiTenancy.setup!(request.host)
        @app.call(env)
      end
    end

    private

    def self.load_map
      db_file = Rails.root.join('config', 'database.yml')
      db_config = YAML.load(ERB.new(File.read(db_file)).result)
      map = { }
      db_config.each do |env, attr|
        next unless env.match(/_#{Rails.env}$/) and attr['adapter'] =~ /^postgresql$/i
        attr['domains'].each { |d| map[d] = attr['schema_search_path'] }
      end
      map
    end

    def self.is_hosted_environment?
      db_file = Rails.root.join('config', 'database.yml')
      db_config = YAML.load(ERB.new(File.read(db_file)).result)
      db_config.select{ |env, attr| Rails.env.to_s.match(/_#{env}$/) }.any?
    end

  end
end