Class: Octopus::ScopeProxy

Inherits:
BasicObject
Includes:
Octopus::ShardTracking::Attribute
Defined in:
lib/octopus/scope_proxy.rb

Defined Under Namespace

Modules: CaseFixer

Instance Attribute Summary collapse

Attributes included from Octopus::ShardTracking::Attribute

#current_shard

Instance Method Summary collapse

Methods included from Octopus::ShardTracking::Attribute

included, #set_current_shard

Constructor Details

#initialize(shard, klass) ⇒ ScopeProxy


18
19
20
21
# File 'lib/octopus/scope_proxy.rb', line 18

def initialize(shard, klass)
  @current_shard = shard
  @klass = klass
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object


46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/octopus/scope_proxy.rb', line 46

def method_missing(method, *args, &block)
  result = run_on_shard { @klass.__send__(method, *args, &block) }
  if result.respond_to?(:all)
    return ::Octopus::ScopeProxy.new(current_shard, result)
  end

  if result.respond_to?(:current_shard)
    result.current_shard = current_shard
  end

  result
end

Instance Attribute Details

#klassObject

Returns the value of attribute klass


12
13
14
# File 'lib/octopus/scope_proxy.rb', line 12

def klass
  @klass
end

Instance Method Details

#==(other) ⇒ Object Also known as: eql?

Delegates to method_missing (instead of @klass) so that User.using(:blah).where(:name => “Mike”) gets run in the correct shard context when #== is evaluated.


61
62
63
# File 'lib/octopus/scope_proxy.rb', line 61

def ==(other)
  method_missing(:==, other)
end

#connectionObject


34
35
36
37
38
39
40
41
42
43
44
# File 'lib/octopus/scope_proxy.rb', line 34

def connection
  @klass.connection_proxy.current_shard = @current_shard

  if @klass.custom_octopus_connection && @klass.allowed_shard?(@current_shard)    # Force use of proxy, given we called 'using' explicitly to get here

    @klass.connection_proxy.current_model = @klass
    @klass.connection_proxy
  else
    @klass.connection
  end
end

#transaction(options = {}, &block) ⇒ Object

Transaction Method send all queries to a specified shard.


30
31
32
# File 'lib/octopus/scope_proxy.rb', line 30

def transaction(options = {}, &block)
  run_on_shard { klass.transaction(options, &block) }
end

#using(shard) ⇒ Object


23
24
25
26
27
# File 'lib/octopus/scope_proxy.rb', line 23

def using(shard)
  fail "Nonexistent Shard Name: #{shard}" if @klass.connection.shards[shard].nil?
  @current_shard = shard
  self
end