Class: ScopedProxy::Proxy

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

Overview

Allows you to create scoped proxies in models.

 Example

class User < ActiveRecord::Base
  scoped_proxy :woman, :find => { :conditions => ['sex=?', 'f'] }

Allowed options

* :exclusive    if set to true, this proxy will not apply if there is another proxy active.

Constant Summary collapse

@@active_proxy =
false

Instance Method Summary collapse

Constructor Details

#initialize(klass, scope = {}, old_scope = nil, options = {}) ⇒ Proxy

Returns a new instance of Proxy.



25
26
27
28
# File 'lib/scoped_proxy.rb', line 25

def initialize(klass, scope={}, old_scope=nil, options={})
  @klass, @scope, @old_scope = klass, scope, old_scope
  @options = options
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/scoped_proxy.rb', line 30

def method_missing(message, *args, &block)
  exclusive_scope = @options[:exclusive] || false
  activate_proxy = (! exclusive_scope) || (exclusive_scope && no_other_proxy_active?)
        
  conditional_scope(@old_scope) do                    # Install previous scope 
    conditional_scope(@scope, activate_proxy) do      # Install this scope
      with_proxy do                                   # Track active proxies
        @klass.send(message, *args, &block)
      end
    end
  end
end

Instance Method Details

#conditional_scope(scope, pred = true) ⇒ Object

Install given scope if it is not nil and the predicate is true. Then yield.



69
70
71
72
73
74
75
76
77
# File 'lib/scoped_proxy.rb', line 69

def conditional_scope(scope, pred=true)
  if scope && pred
    klass_with_scope(@klass, scope) do
      yield
    end
  else
    yield
  end
end

#klass_with_scope(klass, scope, &block) ⇒ Object

Permit access to with_scope from outside the AR::Base class. This is an exception to the rule ;)



81
82
83
# File 'lib/scoped_proxy.rb', line 81

def klass_with_scope(klass, scope, &block)
  klass.send(:with_scope, scope, &block) 
end

#no_other_proxy_active?Boolean

Is there no other proxy than this one active?

Returns:

  • (Boolean)


63
64
65
# File 'lib/scoped_proxy.rb', line 63

def no_other_proxy_active?
  ! self.class.active_proxy
end

#respond_to_with_delegation?(symbol) ⇒ Boolean

Returns:

  • (Boolean)


43
44
45
# File 'lib/scoped_proxy.rb', line 43

def respond_to_with_delegation?(symbol)
  self.respond_to_without_delegation?(symbol) || @klass.respond_to?(symbol)
end

#with_proxyObject

Mark the installation of a proxy. This information can be used to make proxies dependent upon context, as in the default proxy.



51
52
53
54
55
56
57
58
59
# File 'lib/scoped_proxy.rb', line 51

def with_proxy
  begin
    old_value = self.class.active_proxy
    self.class.active_proxy = true
    yield
  ensure
    self.class.active_proxy = old_value
  end
end