DEV Community

n350071πŸ‡―πŸ‡΅
n350071πŸ‡―πŸ‡΅

Posted on • Edited on

model/table name conversions in Rails

πŸ“š Doc ActiveSupport::Inflector module

object to class name

@person.class.name  #=> "Person"
Person.name         #=> "Person"

Class to table name

User.table_name   #=> "users"

tableize

"Person".tableize      # => "people"
"Invoice".tableize     # => "invoices"
"InvoiceLine".tableize # => "invoice_lines"

classify

"people".classify                        # => "Person"
"invoices".classify                      # => "Invoice"
"invoice_lines".classify                 # => "InvoiceLine"
"highrise_production.companies".classify # => "Company"

constantize

"Fixnum".constantize # => Fixnum

pluralize

"table".pluralize     # => "tables"
"ruby".pluralize      # => "rubies"
"equipment".pluralize # => "equipment"

"dude".pluralize      # => "dudes"
"dude".pluralize(0)   # => "dudes"
"dude".pluralize(1)   # => "dude"
"dude".pluralize(2)   # => "dudes"

singularize

"tables".singularize    # => "table"
"rubies".singularize    # => "ruby"
"equipment".singularize # => "equipment"

camelize(camelcase)

"/" converts to "::".

"product".camelize               # => "Product"
"admin_user".camelize            # => "AdminUser"
"backoffice/session".camelize    # => "Backoffice::Session"
"visual_effect".camelize(:lower) # => "visualEffect"

underscore

"::" converts to "/".
I sometimes use it with .gsub(/\//, '_').

"Product".underscore             # => "product"
"AdminUser".underscore           # => "admin_user"
"Backoffice::Session".underscore # => "backoffice/session"
"visualEffect".underscore        # => "visual_effect"

titleize(titlecase)

"alice in wonderland".titleize # => "Alice In Wonderland"
"fermat's enigma".titleize     # => "Fermat's Enigma"

dasherize

"name".dasherize         # => "name"
"contact_data".dasherize # => "contact-data"

demodulize

"Product".demodulize                        # => "Product"
"Backoffice::UsersController".demodulize    # => "UsersController"
"Admin::Hotel::ReservationUtils".demodulize # => "ReservationUtils"
"::Inflections".demodulize                  # => "Inflections"
"".demodulize                               # => ""

deconstantize

"Product".deconstantize                        # => ""
"Backoffice::UsersController".deconstantize    # => "Backoffice"
"Admin::Hotel::ReservationUtils".deconstantize # => "Admin::Hotel"

parameterize

"John Smith".parameterize # => "john-smith"
"Kurt GΓΆdel".parameterize # => "kurt-godel"

πŸ”— Parent Note

Top comments (0)