Class: MultiDB::Organization

Inherits:
ActiveRecord::Base show all
Defined in:
lib/multi_db/organization.rb

Instance Method Summary collapse

Methods inherited from ActiveRecord::Base

connect_to_master, connect_to_organization, connect_to_sessions, master_configuration

Instance Method Details

#connect(set_env = false) ⇒ Object



25
26
27
# File 'lib/multi_db/organization.rb', line 25

def connect(set_env = false)
  ActiveRecord::Base.connect_to_organization(self, set_env)
end

#create_databaseObject



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/multi_db/organization.rb', line 29

def create_database
  if code =~ /^[-\w\d]+$/
    begin
      ActiveRecord::Base.connection.create_database("#{ActiveRecord::Base.configurations[Rails.env]['database']}_#{code}")
    rescue Exception => e
      if e.message =~ /Can't create database '(.*?)'; database exists/
        puts "Warning: database #{$1} already exists"
      else
        throw e
      end
    end
    
    connect
    
    ActiveRecord::Migration.suppress_messages do
      load "#{Rails.root}/db/schema_organization.rb"
    end
  end
end

#drop_database!Object



49
50
51
52
53
54
55
56
57
58
# File 'lib/multi_db/organization.rb', line 49

def drop_database!
  if Rails.env.production?
    raise "Won't drop database in production mode for safety reasons."
  else
    if code =~ /^[-\w\d]+$/
      # watch for sql injection here
      ActiveRecord::Base.connection.drop_database("#{ActiveRecord::Base.configurations[Rails.env]['database']}_#{code}")
    end
  end
end

#ensure_codeObject



12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/multi_db/organization.rb', line 12

def ensure_code
  if code.blank?
    return true unless name
    new_code = name.downcase.gsub(/[^-\w\d]+/, '-')
    self.code = new_code
    i = 2
    while self.class.where(:code => code, :active => true).first
      self.code = "#{new_code}#{i}"
      i += 1
    end
  end
end