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

(Tuis.) #1

86 | Chapter 3: Rails Plugins


class ApplicationController < ActionController::Base
include AccountLocation
end

puts ApplicationController.instance_methods.grep /^account/
=> ["account_domain", "account_subdomain", "account_host", "account_url"]

Including theAccountLocationmodule in the controller allows you to access various
URL options from the controller and the view. For example, to set the@accountvari-
able from the subdomain on each request:


class ApplicationController < ActionController::Base
include AccountLocation
before_filter :find_account

protected

def find_account
@account = Account.find_by_username(account_subdomain)
end
end

Theaccount_locationplugin has noinit.rb; nothing needs to be set up on load, as all
functionality is encapsulated in theAccountLocationmodule. Here is the implemen-
tation, inlib/account_location.rb (minus some license text):


module AccountLocation
def self.included(controller)
controller.helper_method(:account_domain, :account_subdomain,
:account_host, :account_url)
end

protected

def default_account_subdomain
@account.username if @account && @account.respond_to?(:username)
end

def account_url(account_subdomain = default_account_subdomain,
use_ssl = request.ssl?)
(use_ssl? "https://" : "http://") + account_host(account_subdomain)
end

def account_host(account_subdomain = default_account_subdomain)
account_host = ""
account_host << account_subdomain + "."
account_host << account_domain
end

def account_domain
account_domain = ""
account_domain << request.subdomains[1..-1].join(".") +
"." if request.subdomains.size > 1
account_domain << request.domain + request.port_string
end
Free download pdf