Module: MultipleDbs
- Defined in:
- lib/multiple_dbs.rb,
lib/multiple_dbs/railtie.rb,
lib/multiple_dbs/version.rb,
lib/multiple_dbs/multi_connectable.rb,
lib/generators/multiple_dbs_initializer/templates/initializer.rb
Overview
MultipleDbs
The MultipleDbs module.
Defined Under Namespace
Modules: DbConnection, MultiConnectable Classes: Railtie
Constant Summary collapse
- VERSION =
'1.0.0'
Class Method Summary collapse
Class Method Details
.run_setup ⇒ Object
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 |
# File 'lib/multiple_dbs/multi_connectable.rb', line 155 def run_setup Object.class_eval do def self.const_missing(c) matches = [] db_matches = [] MultipleDbs::DBS.each do |db| matches << c.to_s.scan( Regexp.new('(([A-Z]){1}([a-zA-Z]|[0-9])*)+' + db.to_s.camelize + '$') ) db_matches << db break if matches.flatten.any? end const_temp = Object.const_get(matches.first).mdb(db_matches.last) if matches.flatten!.any? MultipleDbs.validate_connection(db_matches.last) if matches.any? and const_temp.to_s.eql?(c.to_s) return const_temp if matches.any? and const_temp.to_s.eql?(c.to_s) super end end if Rails.env.development? and defined? MultipleDbs and defined? MultipleDbs::DBS DBS.each do |db| Object.const_set("DBConnection" + db.to_s.camelize , Class.new do attr_accessor :connection @connection = YAML::load(ERB.new(File.read(Rails.root.join("config/multiple_dbs", db.to_s.downcase + "_database.yml"))).result)[Rails.env] def self.connection @connection end end) end DBS.each do |db| conn_config = const_get("DBConnection" + db.to_s.camelize).connection if conn_config["database"] != ActiveRecord::Base.connection_config[:database] conn_klass = Object.const_set("Conn" + db.to_s.camelize, Class.new(ApplicationRecord)) conn_klass.establish_connection conn_config conn_klass.connection else Object.const_set("Conn" + db.to_s.camelize, ActiveRecord::Base) end end ActiveRecord::Base.clear_all_connections! end |
.validate_connection(db) ⇒ Object
3 4 5 6 7 8 9 10 11 12 13 14 |
# File 'lib/multiple_dbs/multi_connectable.rb', line 3 def validate_connection(db) conn_klass = const_get("Conn#{db.to_s.camelize}") if conn_klass ActiveRecord::Base.connection_handler.connection_pools.each do |pool| Rails.logger.info "CONN FOUND" and return true if pool.spec.name == conn_klass.to_s end Rails.logger.info " CONN NOT FOUND. CONNECTION TO #{conn_klass}" conn_klass.connection and return true else raise Exception.new("Undefined constant #{conn_klass}") end end |