This article will discuss how to implement several helpful string methods in Ruby on Rails: camelize
, classify
, humanize
and inquiry
.
Let’s start with camelize
. This converts the string to upper CamelCase by default, and to lower camelCase if the arguments are given. Also, it converts the paths to a namespace by converting “/” into “::”. Here is an example:
1
2
3
“active_support”.camelize # => “ActiveSupport”
“active_support”.camelize(:lower) # => “activeSupport”
“active_support/errors”.camelize # => “ActiveSupport::Errors”
The next method is classify
. This method is helpful when converting table_names to their model classes in Rails.
1
2
“customers”.classify # => “Customer”
“before_posts”.classify # => “BeforePost”
The humanize
method capitalizes the first letter, converts underscores into spaces, and removes _id
if present (by default) to generate human-friendly output.
1
2
3
4
“start_date”.humanize # => “Start date”
“post_id”.humanize # => “Post”
“_id”.humanize # => “Id”
“post_id”.humanize(keep_id_suffix: true) # => “Post Id”
Finally, another extremely useful method is inquiry
, which is used to check equality.
1
2
3
env = 'production'.inquiry
env.production? # => true
env.development? # => false
Now you can incorporate camelize
, classify
, humanize
and inquiry
into your Rails programming! Happy stringing!