Skip to content

Commit

Permalink
Use connection_pool of abstract base class
Browse files Browse the repository at this point in the history
  • Loading branch information
gussan committed Jan 26, 2015
1 parent 09a28cf commit 401e580
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 23 deletions.
44 changes: 21 additions & 23 deletions lib/active_record/turntable/shard.rb
Original file line number Diff line number Diff line change
@@ -1,48 +1,46 @@
module ActiveRecord::Turntable
class Shard
module Connections; end

DEFAULT_CONFIG = {
"connection" => (defined?(Rails) ? Rails.env : "development")
}.with_indifferent_access

attr_reader :name

def initialize(shard_spec)
@config = DEFAULT_CONFIG.merge(shard_spec)
@name = @config["connection"]
ActiveRecord::Base.turntable_connections[name] = connection_pool
end

def connection_pool
@connection_pool ||= retrieve_connection_pool
connection_klass.connection_pool
end

def connection
connection = connection_pool.connection
connection.turntable_shard_name = name
connection
end

def name
@name
connection_pool.connection.tap do |conn|
conn.turntable_shard_name ||= name
end
end

private

def retrieve_connection_pool
ActiveRecord::Base.turntable_connections[name] ||=
begin
config = ActiveRecord::Base.configurations[Rails.env]["shards"][name]
raise ArgumentError, "Unknown database config: #{name}, have #{ActiveRecord::Base.configurations.inspect}" unless config
ActiveRecord::ConnectionAdapters::ConnectionPool.new(spec_for(config))
end
def connection_klass
@connection_klass ||= create_connection_class
end

def spec_for(config)
begin
require "active_record/connection_adapters/#{config['adapter']}_adapter"
rescue LoadError => e
raise "Please install the #{config['adapter']} adapter: `gem install activerecord-#{config['adapter']}-adapter` (#{e})"
def create_connection_class
if Connections.const_defined?(name.classify)
klass = Connections.const_get(name.classify)
else
klass = Class.new(ActiveRecord::Base)
Connections.const_set(name.classify, klass)
klass.abstract_class = true
end
adapter_method = "#{config['adapter']}_connection"

ActiveRecord::ConnectionAdapters::ConnectionSpecification.new(config, adapter_method)
klass.remove_connection
klass.establish_connection ActiveRecord::Base.connection_pool.spec.config[:shards][name].with_indifferent_access
klass
end
end
end
1 change: 1 addition & 0 deletions spec/support/turntable_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ def establish_connection_to(env = :test)

def truncate_shard
ActiveRecord::Base.descendants.each do |klass|
next if klass.abstract_class?
klass.delete_all
end
end
Expand Down

0 comments on commit 401e580

Please sign in to comment.