90 | Chapter 3: Rails Plugins
def authenticate_with_http_basic(&login_procedure)
HttpAuthentication::Basic.authenticate(self, &login_procedure)
enddef request_http_basic_authentication(realm = "Application")
HttpAuthentication::Basic.authentication_request(self, realm)
end
endThis 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). Here is
the abridged code for the HTTP Authentication plugin’s class methods:
module HttpAuthentication
module Basic
extend self
module ControllerMethods
def authenticate_or_request_with_http_basic(realm = "Application",
&login_procedure)
authenticate_with_http_basic(&login_procedure) ||
request_http_basic_authentication(realm)
enddef authenticate_with_http_basic(&login_procedure)
HttpAuthentication::Basic.authenticate(self, &login_procedure)
enddef request_http_basic_authentication(realm = "Application")
HttpAuthentication::Basic.authentication_request(self, realm)
end
end
end
endNow, the methods are self-contained within HttpAuthentication::Basic::
ControllerMethods. A simple statement in the plugin’sinit.rbfile adds the methods to
ActionController::Base:
ActionController::Base.send :include,
HttpAuthentication::Basic::ControllerMethodsTesting Plugins
Like the rest of Rails, plugins have very mature testing facilities. However, plugin
tests usually require a bit more work than standard Rails tests, as the tests are
designed to be run on their own, outside of the Rails framework. Some things to
keep in mind when writing tests for plugins: