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

« Newer Snippets
Older Snippets »
Showing 11-18 of 18 total

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.

c# IsNumeric method

From Subtext source code - http://subtextproject.com/

public static bool IsNumeric(string text)
{
    return Regex.IsMatch(text,"^\\d+$");
}

Helper to display Rails flashes

If you use the convention of using :notice, :warning and :error with your flashes, then this simple helper will allow you to display your flashes easily, and it supports the storage of ActiveRecord::Errors in flash[:error] as well.

  def display_standard_flashes(message = 'There were some problems with your submission:')
    if flash[:notice]
      flash_to_display, level = flash[:notice], 'notice'
    elsif flash[:warning]
      flash_to_display, level = flash[:warning], 'warning'
    elsif flash[:error]
      level = 'error'
      if flash[:error].instance_of? ActiveRecord::Errors
        flash_to_display = message
        flash_to_display << activerecord_error_list(flash[:error])
      else
        flash_to_display = flash[:error]
      end
    else
      return
    end
    content_tag 'div', flash_to_display, :class => "flash #{level}"
  end

  def activerecord_error_list(errors)
    error_list = '<ul class="error_list">'
    error_list << errors.collect do |e, m|
      "<li>#{e.humanize unless e == "base"} #{m}</li>"
    end.to_s << '</ul>'
    error_list
  end

Creating navigation bars with current section highlight in Rails

UPDATE: I have since packaged this functionality up as a Rails plugin - more information can be found at http://opensource.agileevolved.com

*THE CODE BELOW HAS BEEN DISCOVERED TO HAVE PROBLEMS RUNNING IN PRODUCTION MODE - THIS HAS BEEN FIXED IN THE PLUGIN VERSION OF THIS SNIPPET. PLEASE SEE THE URL ABOVE*

There are many ways of creating navigation bars using XHTML and CSS but the most common method is to create an unordered list of links which are then formatted in a variety of ways using CSS. There are also many ways of highlighting the tab for the current page, some using server-side logic, some using CSS.

This method enables you to create as many navigation lists as you like in your Rails views, giving each navigation list a unique ID which is then referenced using a simple macro in your controller to set the highlighted link.

First of all, we have the main helper function that lets us create our navigation lists - add the following to your application helper:

def navigation_list(links, options={})
  link_html = ''
  links.each do |link|
    class_name = 'navlink'
    class_name << ' current' if current_section(options[:id], link[:text])
    link_html << content_tag('li', link_to(link[:text], link[:url]),
      :id => "nav_#{link[:text].rubify}", :class => class_name)
  end
  content_tag('ul', link_html, :id => "navbar_#{options[:id]}" || 'navigation')
end

private
  def current_section(navigation_id, link_text)
    link_name = link_text.rubify.to_sym
    navigation_id = navigation_id.rubify.to_sym
    return true if (@controller.current_section?(navigation_id, link_name))
  end


As a small aside, you'll notice the above code relies on a small extension to the Ruby String class - create a file called string.rb to your Rails lib/ folder and add the following monkey patch:

class String 
  def rubify
    self.downcase.strip.gsub(' ', '_')
  end
end


Some of the above functionality will become apparent later, but essentially what it does is take an array of links in a specific format (see below) and turn them into an unordered list of links. The function takes an optional :id parameter (which otherwise defaults to 'navigation') which is used as both the HTML ID on the UL element and as an identifier when using the navigation mappings functionality below. Each LI element is given a class of 'navlink' and also a class of 'current' if it is the current link (see below). This provides plenty of hooks for styling in your CSS.

Here is an example usage of the above function:

<%=	navigation_list [
		{ :text => 'Dashboard', :url => { :controller => 'dashboard' },
		{ :text => 'Admin', :url => { :controller => 'admin', :action => 'login' } }
	], :id => 'main_nav' %>


The :text key is the actual link text, and the :url key is the standard set of Rails url_for options. You can create as many of these navigation lists on a page as you want - just be sure to give each one a unique ID.

The other step is to create a way of storing your "navigation mappings" - a hash of navigation list to current link pairs. Add the following to your ApplicationController:

@@navigation_mappings = {}

def self.navigation_section(mapping)
  @@navigation_mappings.merge!(mapping)
end
  
def current_section?(navigation_id, link_name)
  return (@@navigation_mappings[navigation_id] == link_name)
end


You can use the navigation_section macro to specify which link to set as current for a particular navigation list. Using the example navigation list above, if we wanted to set the Dashboard link as current for all the actions in our DashboardController, we would add the following to our controller code:

class DashboardController < ApplicationController
  navigation_section :main_nav => :dashboard
end


Again, you can add as many navigation_section declarations to your controller if you have many navigation lists on your page that you want to control. The key is the ID of the navigation list and the value is a symbol version of the particular link text - for example, 'This is a link' would become :this_is_a_link.

Adding this mapping will add a 'current' class to the LI element for that particular link - you can now use this in your stylesheet to style the current page link appropriately.

Javascript Link Helper

Ruby on Rails helper to create a link tag to 'name' wich execute the 'javascript' statement onclick event. The last both parameters are the same as for link_to.

Helper para o Ruby on Rails para criar um tag de link associado ao 'name' que executa o código 'javascript' no evento onclick. Os últimos dois parâmetros são os mesmos utilizados no link_to

	def javascript_link_to(name, javascript, html_options = nil, *parameters_for_method_reference)
		options = [ :action => @params["action"] ]
		html_options = { :onclick => javascript+"return false" }
		link_to(name, options, html_options, *parameters_for_method_reference)
	end

making functional test failures readable

making functional test failures readable

By zenspider on Rails

Tired of your rails functional test failures being completely unreadable? I'm not terribly fond of rails' assert_tag but it is better than nothing. However, I never like to read something like the following:

expected tag, but no tag found matching {:attributes=>{:action=>"/admin/themes/update/1"}, :tag=>"form"} in:
"<!DOCTYPE [...3k worth of crap cut...]</html>".


Ugh! It just does nothing to help you and since it isn't expressed as a diff, unit_diff is no help in this arena. I have however figured out how to make it much more manageable with the following snippets:

class ApplicationController < ActionController::Base
 def initialize(testing=false)
 super()
 self.class.layout(nil) if testing
 end
 [...]
end

and then in your functional tests:

def setup
 @controller = MyController.new(true)
 [...]
end


Now your failures contain just the content from the page:

expected tag, but no tag found matching {:attributes=>{:action=>"/admin/themes/update/1"}, :tag=>"form"} in:
"\n<ul>\n <li>Name: Blue</li>\n <li>Folder: blue</li>\n <li>Description: A Plain blue theme</li>\n <li>Masthead: Blue</li>\n <li>Editor: n/a</li>\n</ul>\n\n<a href=\"/admin/themes/show/1\">Cancel Editing</a>\n".

ajax_pagination_links

Put in a helper somewhere, and use like this:
<%= ajax_pagination_links @client_pages, {:update => 'search_results', :params => {:search_query => @params[:search_query]} } %>

and just update the div your results (and the above line) are in.
       def ajax_pagination_links(paginator, options={})
         
         options.merge!(ActionView::Helpers::PaginationHelper::DEFAULT_OPTIONS) {|key, old, new| old}
         
         window_pages = paginator.current.window(options[:window_size]).pages
 
         return if window_pages.length <= 1 unless
           options[:link_to_current_page]
         
         first, last = paginator.first, paginator.last
         
         returning html = '' do
           if options[:always_show_anchors] and not window_pages[0].first?
             html << link_to_remote(first.number, :update => options[:update], :url => { options[:name] => first }.update(options[:params] ))
             html << ' ... ' if window_pages[0].number - first.number > 1
             html << ' '
           end
           
           window_pages.each do |page|
             if paginator.current == page && !options[:link_to_current_page]
               html << page.number.to_s
             else
               html << link_to_remote(page.number, :update => options[:update], :url => { options[:name] => page }.update(options[:params] ))
             end
             html << ' '
           end
           
           if options[:always_show_anchors] && !window_pages.last.last?
             html << ' ... ' if last.number - window_pages[-1].number > 1
             html << link_to_remote(paginator.last.number, :update => options[:update], :url => { options[:name] => last }.update( options[:params]))
           end
         end
       end
« Newer Snippets
Older Snippets »
Showing 11-18 of 18 total