This project is archived and is in readonly mode.
DRYing up respond_to: Allow multiple types in same responder
Reported by David Knorr | April 26th, 2009 @ 01:00 PM | in 2.x
Currently, if you have and index action that responds to three different types, html, rss, and atom, and you want the rss and atom versions to use one SQL query and the html to use version another, you might do this:
def index
respond_to do |format|
format.html { @articles = Article.paginate(:page => params[:page]) }
format.atom { find_all_articles }
format.rss { find_all_articles }
end
end
private
def find_all_articles
@articles = Article.find(:all)
end
The patch which is attached to this ticket allows you to do this instead:
def index
respond_to do |format|
format.html { @articles = Article.paginate(:page => params[:page]) }
format.atom_and_rss { @articles = Article.find(:all) }
end
end
In my oppinion this is more readable, and it's DRY and elegant. What do you think? Any ideas to improve this patch is welcomed with open arms. :)
Comments and changes to this ticket
-
David Knorr April 26th, 2009 @ 04:30 PM
@blj: As a groundrule, yes, but you wouldn't paginate an RSS/Atom feed, would you? For example.
-
Jeffrey Hardy April 27th, 2009 @ 01:07 AM
Forgive me if I'm being naive, but can't you use format.any here?
def index respond_to do |format| format.html { @articles = Article.paginate(:page => params[:page]) } format.any(:atom, :rss) { @articles = Article.find(:all) } end end
-
David Knorr April 27th, 2009 @ 06:52 AM
@Jeffrey Hardy: Yes, you can, and I must admit, I wasn't aware of that. But anyway I don't think it invalidates the patch. After all, the patch allows a more elegant syntax, and we can still use the any method as a catch-all type.
-
David Knorr May 15th, 2009 @ 10:45 AM
I would like to get this out of the way. First of all: Has anyone got any comments/questions/suggestions for improvements? If not, could this patch either be applied to core or marked as "wontfix"? Having this hanging around on Lighthouse serves no purpose.
-
Pratik August 9th, 2009 @ 09:52 PM
- Assigned user set to José Valim
Jose : Could u please close if we don't need this anymore ?
-
José Valim August 9th, 2009 @ 09:58 PM
- State changed from new to wontfix
I agree with Jeffrey, any is the official API for several formats. :)
Create your profile
Help contribute to this project by taking a few moments to create your personal profile. Create your profile »
<h2 style="font-size: 14px">Tickets have moved to Github</h2>
The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>