Create a gist now

Instantly share code, notes, and snippets.

@eprothro /octopus.rb
Last active Dec 16, 2015

Octopus initializer for use with master/slave horizontal DB scaling with a Rails application on the Heroku stack. See the wiki page for more info: https://github.com/tchandy/octopus/wiki/Replication-with-Rails-on-Heroku
module Octopus
def self.shards_in(group=nil)
config[Rails.env].try(:[], group.to_s).try(:keys)
end
def self.followers
shards_in(:followers)
end
class << self
alias_method :followers_in, :shards_in
alias_method :slaves_in, :shards_in
end
end
if Octopus.enabled?
count = case (Octopus.config[Rails.env].values[0].values[0] rescue nil)
when Hash
Octopus.config[Rails.env].map{|group, configs| configs.count}.sum rescue 0
else
Octopus.config[Rails.env].keys.count rescue 0
end
puts "=> #{count} #{'database'.pluralize(count)} enabled as read-only #{'slave'.pluralize(count)}"
if Octopus.followers.count == count
Octopus.followers.each{ |f| puts " * #{f.split('_')[0].upcase} #{f.split('_')[1]}" }
end
end
@randomm

Thanks for this!

I'm, however, getting ActiveRecord::ConnectionNotEstablished when none of my models marked as replicated_model. (At this point I do not wish to mark any of my models as such, but rather route specific queries to read only shards.)

Appending this to the file, however, fixes that issue:

if Octopus.enabled?
  Octopus.config[Rails.env]['master'] = ActiveRecord::Base.connection.config
  ActiveRecord::Base.connection.initialize_shards(Octopus.config)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment