Skip to content

Instantly share code, notes, and snippets.

@hryk
Created July 18, 2010 10:43
Show Gist options
  • Select an option

  • Save hryk/480310 to your computer and use it in GitHub Desktop.

Select an option

Save hryk/480310 to your computer and use it in GitHub Desktop.
DbCharmer custom shard method allow you to shard with mod of integer
# DbCharmer custom sharding method.
# :method => :mod
module DbCharmer
module Sharding
module Method
class Mod
attr_accessor :mods
attr_accessor :all
def initialize(config)
@mods = config[:mods] ? config[:mods].clone : raise(ArgumentError, "No :mods defined!")
@all = 0
config[:mods].keys.each do |m|
next if m == :default
@all += 1
end
end
def shard_for_key(key)
return mods[:default] if key == :default
key_mod = key.to_i % all
if mods["mod_#{key_mod.to_s}".to_sym]
return mods["mod_#{key_mod.to_s}".to_sym]
elsif mods[:default]
return mods[:default]
else
raise ArgumentError, "Invalid key value, no shards found for this key!"
end
end
def support_default_shard?
mods.has_key?(:default)
end
end
end
end
end
MOD_SHARDING = {
:mod_0 => :shard_one,
:mod_1 => :shard_two,
:default => :shard_one
}
DbCharmer::Sharding.register_connection(
:name => :sharded_texts,
:method => :mod,
:mods => MOD_SHARDING
)
class Text < ActiveRecord::Base
db_magic :sharded => {
:key => :id,
:sharded_connection => :sharded_texts
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment