-
Website
http://blog.astrails.com/ -
Original page
http://blog.astrails.com/2009/10/27/liberate-my-controller -
Subscribe
All Comments -
Community
-
Top Commenters
-
Craigslist Proxy
1 comment · -1 points
-
westonm
1 comment · 1 points
-
hoornet
1 comment · 1 points
-
borisnadion
2 comments · 1 points
-
astrails
5 comments · 1 points
-
-
Popular Threads
I get around this by having models implement a method called canonical_url that returns an object like so:
{:use_route => "article", :id => self.id}This hash can then be passed to url_for to generate a route. I think this is a good convention for apps like yours that are doing some CMS-y things and necessarily blurring the line between data and views.
class ArticleWidgetPresenter
delegate :link_to, :to => :controller
def initialize(controller, article_id)
@controller, @article = controller, Article.find(article_id)
end
def to_html
# .. load a template, build a string, etc
end
end
And then, in your controller action
def widget
@presenter = ArticleWidgetPresenter.new(self, params[:id])
render :text => @presenter.to_html
end
You could even load the routing module and not need the controller at all.
Lets say I have articles#index returning Article.paginate(:include => :comments).to_xml
with current_controller both Article and Comment can access url_for inside their respective to_xml implementations, and all the rest is done by Rails / ActiveSupport
With your presenter pattern I'll have like X times more code that is much harder to understand and maintain. not simpler.
ArticleXmlList.new(Article.all, request.domain).to_s
Doesn't use Rails' url helpers, but its easily testable, doesn't know about more than it needs to, and works via the console just fine.
Where will your urls point to? http://localhost:3000/ ? :)
Any other solution will require *some* piece of code holding a current_domain and being responsible for creating nice urls to your models. Since we already have such a piece called "controller" I don't see any reason to duplicate it somewhere else :)
Presenter pattern is real nice for this stuff. Especially when a few months down the road you need to write some script, data migration, cronjob, etc... that wants to use your model outside the rails environment.
And having a presenter for every model that I want to return, effectively doubling my class count for the purpose on just to_xml is insane.
No. It's just stupid when you alter the patterns while there are other ways to accomplish what you need. It just means you don't understand what MVC stands for.
'standard' way of implementing respond_to { |w| w.xml ..} in Rails is to call .to_xml.
Its the easiest and cleanest (from readability/maintainability/dry/minimal_loc points of view) solution.
If you need to generate urls inside it (especially if its in some included association) then having current_controller is IMHO the best possible option.