832ed6ace46d61032151f4e1864c057f

It's a Location selector, from Continent till Suburb.
There are a different rules:

* Next selection must appear if only previous level been selected
* If no children on current level, then all next levels show as a text fields
* If level > OPTION_CAPABLE, then must appear option "Other"
* If Other selected, then self and all next levels must show as a text fields

/me start to write tests for this biiig view partial.

Thanks.

acts_as_nested_set
OPTION_CAPABLE = 2
LEVELS = [:continent, :country, :region, :town, :suburb]
<% ancestors = location.self_and_ancestors if location %>

<%= hidden_field_tag 'products[location_id]', location ? location.id : nil %>

<% is_text_field = false %>
<% Location::LEVELS.each_with_index do |level, level_number| %>
  <% previous_ancestor = (ancestors ? ancestors[level_number - 1] : nil) %>
  <% ancestor = (ancestors ? ancestors[level_number] : nil) %>
  <div id="location_<%= level %>_container">
    <% children = (previous_ancestor ? previous_ancestor.children : []) %>
    <% options = (0 == level_number ? Location.roots : children).map { |l| [l.name, l.id] } %>

    <% if options.size > 0 %>
      <%= label_tag :"select_location_#{level}" %>:

      <% options = [[Location.human_attribute_value(:name, :value => :select), '']] + options %>
      <% options += [[Location.human_attribute_value(:name, :value => :other), 0]] if level_number > Location::OPTION_CAPABLE %>

      <%= select_tag :"location_#{level}", options_for_select(options, (ancestor ? ancestor.id : nil) || params[:other].to_i) %> - <%=  (ancestor ? ancestor.id : nil) || params[:other].to_i %><br/>
    <% end %>
    
    <% if (Location::LEVELS.last != level && !ancestor.nil? && ancestor.children.size == 0) || (ancestor.nil? && params[:other]) || is_text_field %>
      <% is_text_field = true %>

      <% unless !ancestor.nil? && ancestor.children.size == 0 %>
        <%= label_tag :"type_location_#{level}" %>:
        <%= text_field_tag :a, :a %>
      <% end %>
    <% end %>
  </div>
<% end %>

Refactorings

No refactoring yet !

F1e3ab214a976a39cfd713bc93deb10f

Tj Holowaychuk

May 14, 2009, May 14, 2009 15:50, permalink

1 rating. Login to rate!

Gah I cant even look at ERB its so nasty. First of all I would drop the brackets im not sure why everyone does that ie:

LEVELS = :continent, :country, :region, :town, :suburb

Your refactoring





Format Copy from initial code

or Cancel