8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
# File 'lib/nightcrawler/shard_descriptor.rb', line 8
def self.included(klass)
class << klass
def shard(key)
Nightcrawler::ShardDescriptor.shard_mutex.synchronize do
shard_cache[key] ||= create_shard(key)
end
end
def shard_cache
@shard_cache ||= {}
end
attr_reader :shard_criteria, :manager, :shard_behavior
def shard_behavior(&block)
@behavior = block
end
def managed_by(manager)
@manager = manager
end
def defined(file, line, method)
manager.shard_descriptions.each do |key, config|
shard_cache[key] = create_shard(key)
end
end
def shard_by(key)
@shard_criteria = key
end
def create_shard(key)
raise "No shard for key: #{key.inspect}" unless manager.shard(key)
klass = Class.new manager.shard(key)
if self.name.split("::").length > 1
class_name = manager.prefix + key.to_s + self.name.split("::").last
_module = class_name.split("::").first
_klass = class_name.split("::").last
eval(_module).module_eval{self.const_set _klass, klass}
else
Object.const_set class_name, klass
end
klass.class_eval do
include Nightcrawler::Shard
class << self
attr_accessor :shard_id, :class_prefix, :described_by
end
end
klass.shard_id = key
klass.class_prefix = manager.prefix + key.to_s
klass.class_eval(&@behavior)
klass.described_by = self
klass
end
end
end
|