Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

classify() for alternating rows, columns, etc.

I often want different rows in a table to alternate in color, and I do this by assigning each row a class name and styling it with CSS. This is a simple helper method designed to return a class name based on the given row count.

It is also convenient for me to assign a class to table cells based on the type of content they hold. For example, if I have a cell with a float value in it, I want to display it with a monospace font, whereas if I have a cell with a string in it, I want to display it in a serif font.

# Determines the CSS class based on either the count given
# (returns 'even' or 'odd' as the CSS class name) or the class
# given (returns the string version of the class, lowercased,
# as the CSS class name)
def classify( count_or_class, include_class_text = true )
  if count_or_class.class == Fixnum
    value = ( count_or_class % 2 == 0 ? 'even' : 'odd' )
  else
    value = count_or_class.to_s.downcase
  end

  if include_class_text
    'class="' << value << '"'
  else
    value
  end
end


Example usage with alternating 'even'/'odd' row class names:
<table>
<% count = 0 %>
<% @collection.each do |value| %>
  <tr <%= classify( count ) %>>
    <td><%=h value %></td>
  </tr>
  <% count += 1 %>
<% end %>
</table>


Example usage with data type class names:
<tr>
<% @columns.each do |column| %>
  <% data = row.send( column.name ) %>
  <td <%= classify( data.class ) %>>
    <%=h data %>
  </td>
<% end %>
</tr>

helper to determine if radio/checkbox needs to be checked

I frequently have to use methods such as 'radio_button' and 'check_box_tag' when I don't have an object with a method that will automatically determine the value of the input field. Therefore, I have to check to see if a certain parameter has been passed, and if so, if the parameter's value matches that of the input's value. This method does that.

It's designed to be used in a Rails helper. You can either pass it the object, method, and value (the same parameters as, for example, radio_button) or name and value (the same parameters as radio_button_tag).

def checked?( *args )
  if args.length == 3
    object, method, value = args
    if params[object] && params[object][method] && params[object][method] == value
      'checked'
    end
  elsif args.length == 2
    name, value = args
    if params[name] && params[name] == value
      true
    end
  end
end


Here's an example usage:
<%= radio_button 'person', 'age', '12', :checked => checked?( 'person', 'age', '12' ) %>


If params[:person][:age] exists and it equals '12', then 'checked?' returns 'checked'; otherwise, it returns nil.
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS