Class: ActiveShard::Scope

Inherits:
Object
  • Object
show all
Defined in:
lib/active_shard/scope.rb

Overview

Maintains the state of current active shards per schema.

Requests for the current active shard for a schema name will iterate up the scope stack until it finds an active shard (or nil).

Examples:

scope = Scope.new
scope.push( :user_data => :db_1, :directories => :directory_1 )

# updates current :user_data shard, :directories shard remains
scope.push( :user_data => :db_3 )

scope.active_shard_for_schema( :user_data )
=> :db_3

scope.active_shard_for_schema( :directories )
=> :directory_1

Defined Under Namespace

Classes: AnyShard, Memento

Instance Method Summary collapse

Constructor Details

#initializeScope

Returns a new instance of Scope.



23
24
25
26
# File 'lib/active_shard/scope.rb', line 23

def initialize
  @scope_crumbs   = []
  @current_shards = {}
end

Instance Method Details

#active_shard_for_schema(schema_name) ⇒ Symbol?

Returns the name of the active shard by the provided schema name.

Parameters:

  • schema_name (Symbol)

    name of schema

Returns:

  • (Symbol, nil)

    current active shard for schema



79
80
81
# File 'lib/active_shard/scope.rb', line 79

def active_shard_for_schema( schema_name )
  current_shards[ schema_name.to_sym ] || current_shards[ AnyShard ]
end

#pop(memento = nil) ⇒ Object

Remove the last scope from the stack

FIXME: Symbols (for AnySchema) may not roll back properly if multiple

the same symbol is on the stack several times


63
64
65
66
67
68
69
70
71
# File 'lib/active_shard/scope.rb', line 63

def pop( memento=nil )
  if memento.nil?
    scope_crumbs.pop

    build_current_shards( scope_crumbs )
  else
    restore_from_memento!( memento )
  end
end

#push(active_shards) ⇒ Scope::Memento

Push a new scope on onto the stack.

The active_shards parameter should be a hash with schema names for keys and shard names for the corresponding values.

eg: scope.push( :directory => :dir1, :user_data => :db1 )

Parameters:

  • active_shards (Hash)

Returns:

  • (Scope::Memento)

    memento object to pass back to pop() to revert scope state.



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/active_shard/scope.rb', line 39

def push( active_shards )
  previous_state_memento = to_memento()

  scope_crumbs << active_shards

  # shortcutting #build_current_shards for performance reasons
  if active_shards.is_a?(Symbol)
    # if active_shards is a Symbol, ALL schemas are using active shard
    current_shards.keys.each do |schema|
      current_shards[schema] = active_shards
    end
    current_shards[AnyShard] = active_shards
  else
    current_shards.merge!( normalize_keys( active_shards ) )
  end

  previous_state_memento
end