Including Url Helpers in Models

The title itself may set off alarm bells among MVC purists and I agree that it is a clear violation of the MVC pattern. In an ideal world there shouldn’t be any url generation done in the models and if the need arises for the use url_helpers in your model then one can safely assume that something is not how its supposed to be.

One of my personal projects had me generate urls from my model for a post which was to be passed on to a Twitter module to be posted as a tweet. Now clearly the data generation belongs to the model and hence I concluded that this is where the code belongs.

So how do we get the UrlHelpers in the model

Before Rails 3 it was

 include ActionController::UrlWriter

and assuming that you have the default_url_options for host set you could access any url.

In Rails 3 ActionController::UriWriter is deprecated and what needs to be included is

include Rails.application.routes.url_helpers 

and everything works as advertised.

Rails version 3.0.1 actively includew Rails.application.routes.url_helpers with deprecation warnings on inclusion of ActionController::UrlWriter

I am sure there is a more elegant work around to do this but till I figure it out this should work.