Class: Keycard::ReloadableProxy

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

Overview

A proxy for class methods, as for authentication methods on User/Account models. This is useful primarily during development mode, where binding a finder into a Verfication factory can break because of code reloading.

For example, something like this would fail across requests where the User model is saved (in development): ‘AuthToken.bind(User.public_method(:authenticate_by_auth_token))`.

Instead, you can bind to a class method with a proxy that will catch the error from Rails thrown when using a stale reference, replace the target method, and retry the call transparently.

Examples:

callable = ReloadableProxy.new(:User, :authenticate_by_auth_token)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(classname, methodname) ⇒ ReloadableProxy

Returns a new instance of ReloadableProxy.



21
22
23
24
25
# File 'lib/keycard/reloadable_proxy.rb', line 21

def initialize(classname, methodname)
  @classname = classname
  @methodname = methodname
  lookup
end

Instance Attribute Details

#classnameObject (readonly)

Returns the value of attribute classname.



19
20
21
# File 'lib/keycard/reloadable_proxy.rb', line 19

def classname
  @classname
end

#methodnameObject (readonly)

Returns the value of attribute methodname.



19
20
21
# File 'lib/keycard/reloadable_proxy.rb', line 19

def methodname
  @methodname
end

#targetObject (readonly)

Returns the value of attribute target.



19
20
21
# File 'lib/keycard/reloadable_proxy.rb', line 19

def target
  @target
end

Instance Method Details

#call(*args) ⇒ Object

Call the proxied class method, looking it up again if the class has been reloaded (as signified byt he ArgumentError Rails raises).



29
30
31
32
33
34
# File 'lib/keycard/reloadable_proxy.rb', line 29

def call(*args)
  target.call(*args)
rescue ArgumentError
  lookup
  target.call(*args)
end

#lookupObject



36
37
38
# File 'lib/keycard/reloadable_proxy.rb', line 36

def lookup
  @target = Object.const_get(classname).method(methodname)
end