Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1
Plugin Examples | 87

def account_subdomain
request.subdomains.first
end
end

Theself.includedmethod is a standard idiom for plugins; it is triggered after the
module is included in a class. In this case, that method marks the included instance
methods as Rails helper methods, so they can be used from a view.


Finally, remember thatDependencies.loadpathscontains thelibdirectories of all
loaded plugins, so the act of mentioningAccountLocationsearches foraccount

location.rbamong thoselibdirectories. Because of this, you do not need torequire
anything in order to use the plugin—just drop the code intovendor/plugins.


SSL Requirement


Thessl_requirementplugin allows you to specify certain actions that must be pro-
tected by SSL. This plugin conceptually divides actions into three categories:


SSL Required
All requests to this action must be protected by SSL. If this action is requested
without SSL, it will be redirected to use SSL. Actions of this type are specified
with thessl_required class method.


SSL Allowed
SSL is allowed on this action but not required. Actions of this type are specified
by thessl_allowed class method.


SSL Prohibited
SSL is not allowed for this action. If an action is not marked withssl_requiredor
ssl_allowed, SSL requests to that action will be redirected to the non-SSL URL.


In typical Rails fashion, the methods that specify SSL requirements are a declarative
language. They specifywhatthe requirements are, nothowto enforce them. This
means that the code reads very cleanly:


class OrderController < ApplicationController
ssl_required :checkout, :payment
ssl_allowed :cart
end

Like theaccount_locationplugin, thessl_requirementplugin is enabled by includ-
ing a module. TheSslRequirement module contains the entire SSL requirement logic:


module SslRequirement
def self.included(controller)
controller.extend(ClassMethods)
controller.before_filter(:ensure_proper_protocol)
end

module ClassMethods
def ssl_required(*actions)
Free download pdf