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

(Tuis.) #1

88 | Chapter 3: Rails Plugins


write_inheritable_array(:ssl_required_actions, actions)
end

def ssl_allowed(*actions)
write_inheritable_array(:ssl_allowed_actions, actions)
end
end

protected

def ssl_required?
(self.class.read_inheritable_attribute(:ssl_required_actions) || []).
include?(action_name.to_sym)
end

def ssl_allowed?
(self.class.read_inheritable_attribute(:ssl_allowed_actions) || []).
include?(action_name.to_sym)
end

private

def ensure_proper_protocol
return true if ssl_allowed?

if ssl_required? && !request.ssl?
redirect_to "https://" + request.host + request.request_uri
return false
elsif request.ssl? && !ssl_required?
redirect_to "http://" + request.host + request.request_uri
return false
end
end
end

Again, the SslRequirement.includedmethod is triggered when SslRequirementis
included in a controller class. Theincludedmethod does two things here. First, it
extends the controller with theSslRequirement::ClassMethodsmodule, to include the
ssl_requiredandssl_allowedclass methods.This is a common Ruby idiom for add-
ing class methods, and it is required because module methods of an included module do
not become class methods of the including class. (In other words,ssl_requiredand
ssl_allowedcould not be module methods ofSslRequirement, because they would not
be added as class methods of the controller class.)


The second thing thatSslRequirement.includeddoes is to set up abefore_filteron
the controller to enforce the SSL requirement. This filter redirects to the properhttp://
orhttps:// URL, depending on the logic declared by the class methods.

Free download pdf