I am in the middle of migrating my application from using subdirectories for userspace to subdomains (ie. domain.com/~user to user.domain.com). I’ve got a method in my user class currently to get the “home” URL for each user:
class User
def home_url
"~#{self.username}"
# How I'd like to do it for subdomains:
#"http://#{self.username}.#{SubdomainFu.host_without_subdomain(request.host)}"
end
end
I’d like to update this for subdomains, but without hardcoding the domain into the method. As you can see, I am using the subdomain-fu plugin, which provides some methods that I could use to do this, except that they need access to request, which is not available to the model.
I know it’s considered bad form to make request available in a model, so I’d like to avoid doing that, but I’m not sure if there’s a good way to do this. I could pass the domain along every time the model is initialized, I guess, but I don’t think this is a good solution, because I’d have to remember to do so every time a class is initialized, which happens often.
While molf’s answer is good, it did not solve my specific problem as there were some instances where other models needed to call
User#home_url, and so there would be a lot of methods I’d have to update in order to pass along the domain.Instead, I took inspiration from his last paragraph and added a
base_domainvariable to my app’s config class, which is the set in abefore_filterinApplicationController:And thus, when I need to get the domain in a model, I can just use
App.base_domain.