Created
July 18, 2010 10:43
-
-
Save hryk/480310 to your computer and use it in GitHub Desktop.
DbCharmer custom shard method allow you to shard with mod of integer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | |
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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