Re: How to clean up this code?

Patrick Doyle
Fri, 28 Mar 2008 19:24:14 -0000

Well, I''ve managed to clean up the code to:

=======================================class DocumentsController <
ApplicationController
  CATEGORIES     [{:id => 0, :text => ''All'', :min=>0,
:max => 99},
     {:id => 1, :text => ''Standard Operating
Procedures'', :min=>0, :max =>0},
     {:id => 2, :text => ''Functional Group Policies and
Procedures'',
:min => 1, :max => 1},
     {:id => 3, :text => ''Project Level Documentation'',
:min => 2, :max => 9},
     {:id => 4, :text => ''Software Documentation'', :min
=> 10, :max => 19},
    ]
  CATEGORIES_FOR_SELECT = CATEGORIES.collect {|c| [c[:text], c[:id]]}

  active_scaffold :document do |config|
  # ...
  end

  # GET /documents
  # GET /documents.xml
  def index
    if params[:category]
      @category = params[:category].to_i
      min = CATEGORIES[@category][:min]
      max = CATEGORIES[@category][:max]
      @condition = "document_number_prefix >= #{min} AND
document_number_prefix <= #{max}"
    end
    @CATEGORIES = CATEGORIES_FOR_SELECT
    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @documents }
    end
  end
end
====================================for my controller, and, for my template:

====================================<%= content_tag :h1, "Document
Log" %>
<% content_tag :fieldset do -%>
  <% form_tag({:action => :index}, {:method => :get}) do -%>
    <%= content_tag :legend, "Document Category" %>
    <%= select_tag ''category'',
options_for_select(@CATEGORIES, @category) %>
    <%= submit_tag ''Go'', :name => nil %>
  <% end -%>
<% end -%>


  <%= render :active_scaffold => :documents, :conditions => @condition
%>

=====================================
and I''m happier with this... While I don''t know the future,
it''s not
likely that the categories will change during the lifetime of the
code.  There are other bits and pieces of code that are likely to be
dependent upon this particular document categorization strategy.  And,
while I could be accused of premature optimization, I like the idea of
passing a constant array to my view instead of invoking a database
query to display constant information.

Now I need to go learn about haml and see if that makes my view of the
template happier.

Thanks again for your insights.