From: Giles Bowkett Date: 2006-11-01T08:26:02+09:00 Subject: still more relentless non-repetition ok, I have this Rails code which I want to make more Rubyish. controller: def tracks @term = params[:term] || '' if @term.blank? @tracks = [] else @tracks = Track.find_by_contents @term end end view: <% for word in %w{ tracks beats users profiles } %> <% unless controller.action_name == word %> <%= link_to "search similar #{word}", :action => word, :term => @term %>
<% end %> <% end %> now this is using Ferret, the Ruby port of Lucene, via the acts_as_ferret Rails plugin. (by the way, Ferret actually runs faster than Lucene, according to the Ferret site. I don't know how, but that's pretty cool.) anyway, as you can see, I have one method in the controller and a view which assumes the existence of three additional methods. what I want to do is have only one method in the controller, which does all the searching. now I could do: def tracks @term = params[:term] || '' case params[:thing_to_search_for] when "tracks" if @term.blank? @tracks = [] else @tracks = Track.find_by_contents @term end when "beats" if @term.blank? @beats = [] else @beats = Beat.find_by_contents @term end when "profiles" if @term.blank? @profiles = [] else @profiles = Profile.find_by_contents @term end when "users" if @term.blank? @users = [] else @users = User.find_by_contents @term end end end however, this is what Rails users call "wet" and everybody else calls "stupid." what I want to do is a properly elegant thingy. here's roughly what I envision: def search @term = params[:term] || '' instance_variable_set("@#{params[:thing_to_search_for]}", []) unless @term.blank? eval("@#{params[:thing_to_search_for]}") = (eval(params[:thing_to_search_for].capitalize)).find_by_contents @term end end I think I should probably just start coding in Lisp and save everyone the irritation, but in the meantime, how does that look, in terms of a tree to bark up? that is to say, does it look like the right tree, or the wrong tree? if you can puzzle it through, I think what I have here is an elegant algorithm expressed in very-much-other-than-elegant code. (but I could be wrong!) -- Giles Bowkett http://www.gilesgoatboy.org