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 

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.

go from model to associated table name and back

Given a table object, it returns the related string object; e.g. SubAttribute => 'sub-attribute'. Useful if you want to make a list of all your tables with perhaps their fields listed out to the side.

def stringify_table( table, replace_char = '-', pluralize = false )
  string = table.to_s.gsub( /([A-Za-z])([A-Z])/, '\1' << replace_char.to_s << '\2' )
  string = string.pluralize if pluralize
  string
end


Given a string akin to the name of a table, it returns the related table object; e.g. 'sub_attributes' => SubAttribute.

def tablify_string( string )
  eval( string.to_s.gsub( /_id/, '' ).singularize.split( '_' ).collect { |word| word.capitalize }.join )
end
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS