Prev | Current Page 131 | Next

Brad Ediger

"Advanced Rails"


The following is a typical use of the HTTP Authentication plugin:
class PrivateController < ApplicationController
before_filter :authenticate
def secret
render :text => "Password correct!"
end
protected
def authenticate
authenticate_or_request_with_http_basic do |username, password|
username == "bob" && password == "secret"
end
end
end
Notice that, unlike the two plugins described earlier, here we did not have to include
anything in the PrivateController??”the authenticate_or_request_with_http_basic
method was already provided for us. This is because the plugin added some methods
to ActionController::Base (of which ApplicationController is a subclass).
One way to include methods like this is direct monkeypatching. The plugin could
have directly written the methods into ActionController::Base:
class ActionController::Base
def authenticate_or_request_with_http_basic(realm = "Application",
&login_procedure)
authenticate_with_http_basic(&login_procedure) ||
request_http_basic_authentication(realm)
end
90 | Chapter 3: Rails Plugins
def authenticate_with_http_basic(&login_procedure)
HttpAuthentication::Basic.authenticate(self, &login_procedure)
end
def request_http_basic_authentication(realm = "Application")
HttpAuthentication::Basic.authentication_request(self, realm)
end
end
This works for small plugins, but it can get clunky. The better solution, chosen by
this plugin, is to first create a module named for the plugin (sometimes including the
developer??™s name or company to reduce the chance of namespace collisions).


Pages:
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143