DEV Community


Discussion on: Rails helper methods to change the form of strings

djuber profile image
Daniel Uber

Great write-up! I've seen the output of dasherize half-jokingly called "kebab-case" to contrast from "camelCase" or "snake_case", but it's pretty uncommon outside of Clojure and other lisps to use it often.

There are a few more string inflection methods listed in the guide but they are probably more likely to be used in backend code or meta-programming than in the front end (I could be wrong!). I think all of these (apart from parameterize) expect a constant name like a class name or module name, so you're dealing with transformations to strings that are expected to be code and not arbitrary input.

  • parameterize turns a string into a url-safe slug/path-component.
"John Smith".parameterize # => "john-smith"
"Kurt Gödel".parameterize # => "kurt-godel"
Enter fullscreen mode Exit fullscreen mode
  • demodulize returns the part of a class/constant that's local to the namespace (it removes all the module information and just returns the last part of the name)
"Product".demodulize                        # => "Product"
"Backoffice::UsersController".demodulize    # => "UsersController"
"Admin::Hotel::ReservationUtils".demodulize # => "ReservationUtils"
"::Inflections".demodulize                  # => "Inflections"
"".demodulize                               # => ""
Enter fullscreen mode Exit fullscreen mode
  • deconstantize does the opposite - it captures the path to the constant without the constant name (top level constants return an empty string)
"Product".deconstantize                        # => ""
"Backoffice::UsersController".deconstantize    # => "Backoffice"
"Admin::Hotel::ReservationUtils".deconstantize # => "Admin::Hotel"
Enter fullscreen mode Exit fullscreen mode
  • foreign_key is used to turn an associated model class into a default column name to find the id - this probably is used in the same layer as tableize in ActiveRecord's internals
"User".foreign_key           # => "user_id"
"InvoiceLine".foreign_key    # => "invoice_line_id"
"Admin::Session".foreign_key # => "session_id"
Enter fullscreen mode Exit fullscreen mode
junko911 profile image
Junko T. Author

Thank you, Daniel! I wasn't aware of those. Awesome!