Module: ActiveRecord::Sharding::Model::ClassMethods

Defined in:
lib/active_record/sharding/model.rb

Instance Method Summary collapse

Instance Method Details

#all_shardsObject



58
59
60
# File 'lib/active_record/sharding/model.rb', line 58

def all_shards
  shard_repository.all
end

#all_shards_in_parallelObject Also known as: parallel



62
63
64
# File 'lib/active_record/sharding/model.rb', line 62

def all_shards_in_parallel
  AllShardsInParallel.new(all_shards)
end

#before_put(&block) ⇒ Object



30
31
32
# File 'lib/active_record/sharding/model.rb', line 30

def before_put(&block)
  @before_put_callback = block
end

#define_parent_methods(&block) ⇒ Object



67
68
69
# File 'lib/active_record/sharding/model.rb', line 67

def define_parent_methods(&block)
  instance_eval(&block)
end

#define_sharding_key(column) ⇒ Object



26
27
28
# File 'lib/active_record/sharding/model.rb', line 26

def define_sharding_key(column)
  self.sharding_key = column.to_sym
end

#put!(attributes) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/active_record/sharding/model.rb', line 34

def put!(attributes)
  raise "`sharding_key` is not defined. Use `define_sharding_key`." unless sharding_key

  @before_put_callback.call(attributes) if @before_put_callback

  if key = attributes[sharding_key] || attributes[sharding_key.to_s]
    if block_given?
      shard_for(key).transaction do
        object = shard_for(key).create!(attributes)
        yield(object)
      end
    else
      shard_for(key).create!(attributes)
    end
  else
    raise ActiveRecord::Sharding::MissingShardingKeyAttribute
  end
end

#shard_for(key) ⇒ Object



53
54
55
56
# File 'lib/active_record/sharding/model.rb', line 53

def shard_for(key)
  connection_name = cluster_router.route key
  shard_repository.fetch connection_name
end

#use_sharding(name, algorithm = :modulo) ⇒ Object



17
18
19
20
21
22
23
24
# File 'lib/active_record/sharding/model.rb', line 17

def use_sharding(name, algorithm = :modulo)
  config = ActiveRecord::Sharding.config.fetch_cluster_config name
  if algorithm == :modulo
    self.cluster_router = ActiveRecord::Sharding::ModuloRouter.new config
  end
  self.shard_repository = ActiveRecord::Sharding::ShardRepository.new config, self
  self.abstract_class = true
end