B78453e586d294bcd297f8ec44ec3458

I wanted A to Z anchor links at the top of the page to include the full alphabet but only to link when there is related content below. Can this be made better somehow?

Controller

1
2
3
@a_to_z = Service.find(:all,:select=>'SUBSTR(name,1,1) AS letter',:group=>'SUBSTR(name,1,1)',:order=>'name').collect { |d| d.letter }


View

1
2
3
4
5
<ul class="pagination">
<% for letter in 'A'..'Z' %>
	<li><%= @a_to_z.index(letter) ? link_to(letter,:l=> letter) : content_tag(:a,letter,:class=>'f') %></li>
<% end %>
</ul>

Refactorings

No refactoring yet !

E635ccff7389d9070f5e7e9fe8b36beb

rpheath

January 14, 2008, January 14, 2008 16:44, permalink

2 ratings. Login to rate!

Well, not a major refactoring, but a bit of cleanup and suggestions as to how I'd probably do it...

service.rb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Service < ActiveRecord::Base
  class << self
    def letters
      find(
        :all,
        :select => 'SUBSTR(name, 1, 1) AS letter',
        :group  => 'SUBSTR(name, 1, 1)',
        :order  => 'name'
      )
    end
    # ... (other class methods)
  end
  # ... (other instance methods)
end

service_controller.rb

1
2
@a_to_z = Service.letters.collect { |d| d.letter }

view

1
2
3
4
5
6
<ul class='pagination'>
  <% ('A'..'Z').each do |letter| -%>
    <%= letter_link_for(@a_to_z, letter) -%>
  <% end -%>
</ul>

service_helper.rb (or application_helper.rb, depending)

1
2
3
4
def letter_link_for(letters, letter)
  content_tag :li, (letters.index(letter) ? link_to(letter, :l=> letter) : content_tag(:a, letter, :class => 'f'))
end

Your refactoring





Format Copy from initial code

or Cancel