From: Giles Bowkett Date: 2006-11-01T15:45:10+09:00 Subject: Re: still more relentless non-repetition OK. here's what I have. def index @term = params[:term] || '' @category = params[:category] || '' if not %w{ Track Beat User Profile }.include? @category redirect_to "/" else instance_variable_set("@#{@category.downcase.pluralize}", (@category.constantize.find_by_contents @term)) end end index view: <%= render_partial @category.downcase.pluralize %> <%= render_partial "options" %> options partial: <% for word in %w{ tracks beats users profiles } %> <% if eval("@#{word}").nil? %> <%= link_to "search similar #{word}", :action => "index", :term => @term, :category => word.capitalize.singularize %>
<% end %> <% end %> the code in the model-specific partials is design-specific, but it picks up the instance vars, which is all that matters in this context. obviously I am using eval and instance_variable_set in ways I'm not supposed to, but in both cases they're filtered in such a way as to prevent harm. actually, if that still seems risky to anybody, I would like to know. I think it's probably OK but I could easily be guilty of overconfidence. I don't like all the upcasing and downcasing. it's not as elegant as it could be. what I do like about it is that it generates a lot of HTML without very much Ruby at all. that's pretty good bang for the buck. in one short method and two quick partials, you have all the code necessary to generate four different types of model-specific search pages, plus links for searching different models with the same query. obviously the array of words could be an instance var, and could be aribtrarily large, but only if I fixed the upcasing and downcasing. -- Giles Bowkett http://www.gilesgoatboy.org