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.

Ruby

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.

Ruby

def tablify_string( string )
  eval( string.to_s.gsub( /_id/, ” ).singularize.split( ‘_’ ).collect { |word| word.capitalize }.join )
end

This entry was cross-posted to my Code Snippets page.

This entry was posted in Programming and tagged , | Current music Passenger Seat by Death Cab for Cutie. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>