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

go from model to associated table name and back (See related posts)

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

Comments on this post

cayblood posts on Aug 28, 2006 at 13:15
Where is the best place to add these methods? app/controllers/application.rb?
moneypenny posts on Aug 31, 2006 at 18:11
That's generally where I put them, yes. It just depends on the scope of where you need them, however. If you're only going to use them in, say, FuzzyController, then put them there. I put them in ApplicationController because I use them in various places throughout my other controllers.

If you need them in both helpers and controllers, it's best to put them in app/helpers/application_helper.rb and then use this tutorial to make them accessible inside controllers.
Flenser posts on Nov 26, 2007 at 12:44
There are Rails helpers for these functions: classify and tableize. No need to write your own!

You need to create an account or log in to post comments to this site.


Click here to browse all 4863 code snippets

Related Posts