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
This entry was cross-posted to my Code Snippets page.
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
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
eval( string.to_s.gsub( /_id/, ” ).singularize.split( ‘_’ ).collect { |word| word.capitalize }.join )
end
This entry was cross-posted to my Code Snippets page.