Class: String

Inherits:
Object show all
Defined in:
lib/core_ext/blank.rb,
lib/core_ext/string.rb

Overview

The inflector extension adds inflection instance methods to String, which allows the easy transformation of words from singular to plural, class names to table names, modularized class names to ones without, and class names to foreign keys. It exists for backwards compatibility to legacy Sequel code.

To load the extension:

Defined Under Namespace

Modules: Inflections

Constant Summary collapse

BLANK_RE =
/\A[[:space:]]*\z/

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.inflections {|Inflections| ... } ⇒ Inflections

Provides access to the Inflections module for defining custom inflection rules. If a block is given, yields the Inflections module to the block. Always returns the Inflections module.

Examples:

Define custom inflection rules

String.inflections do |inflect|
  inflect.plural /^(ox)$/i, '\1\2en'
  inflect.singular /^(ox)en/i, '\1'
end

Yields:

  • (Inflections)

    The Inflections module if a block is given

Returns:



212
213
214
215
# File 'lib/core_ext/string.rb', line 212

def self.inflections
  yield Inflections if defined?(yield)
  Inflections
end

Instance Method Details

#blank?true, false

Returns true if the string consists entirely of whitespace characters

Examples:

A basic example


''.blank?       # => true
'   '.blank?    # => true
"\t\n\r".blank? # => true
' blah '.blank? # => false

Unicode whitespace support


"\u00a0".blank? # => true

Returns:

  • (true, false)

    true if string is empty or only whitespace, false otherwise



125
126
127
# File 'lib/core_ext/blank.rb', line 125

def blank?
  BLANK_RE === self
end

#camelize(first_letter_in_uppercase = :upper) ⇒ String Also known as: camelcase

Converts the string to CamelCase format.

  • Replaces forward slashes with double colons (e.g. ‘foo/bar’ -> ‘Foo::Bar’)

  • Converts underscores to camelized format (e.g. ‘foo_bar’ -> ‘FooBar’)

Examples:

Convert to UpperCamelCase

"active_record".camelize #=> "ActiveRecord"

Convert to lowerCamelCase

"active_record".camelize(:lower) #=> "activeRecord"

Convert path to namespace

"active_record/errors".camelize #=> "ActiveRecord::Errors"

Parameters:

  • first_letter_in_uppercase (Symbol) (defaults to: :upper)

    Whether first letter should be uppercase (:upper) or lowercase (:lower)

Returns:

  • (String)

    The camelized string



235
236
237
238
239
240
# File 'lib/core_ext/string.rb', line 235

def camelize(first_letter_in_uppercase = :upper)
  s = gsub(%r{/(.?)}) { |x| "::#{x[-1..].upcase unless x == "/"}" }
      .gsub(/(^|_)(.)/) { |x| x[-1..].upcase }
  s[0...1] = s[0...1].downcase unless first_letter_in_uppercase == :upper
  s
end

#classifyString

Converts a string into a class name by removing any non-final period and subsequent characters, converting to singular form, and camelizing. Commonly used to obtain class name from table or file names.

Examples:

Convert database table name to class name

"egg_and_hams".classify #=> "EggAndHam"

Remove schema prefix

"schema.post".classify #=> "Post"

Basic conversion

"post".classify #=> "Post"

Returns:

  • (String)

    A camelized singular form suitable for a class name



258
259
260
# File 'lib/core_ext/string.rb', line 258

def classify
  sub(/.*\./, '').singularize.camelize
end

#constantizeObject

Finds and returns a Ruby constant from a string name. The string must be a valid constant name in CamelCase format. Can handle namespaced constants using double colons (::). Raises NameError if the constant name is invalid or not defined.

Examples:

Get Module class

"Module".constantize #=> Module

Get namespaced constant

"ActiveRecord::Base".constantize #=> ActiveRecord::Base

Invalid constant name

"invalid_name".constantize #=> NameError: invalid_name is not a valid constant name!

Returns:

  • (Object)

    The Ruby constant corresponding to the string name

Raises:

  • (NameError)

    If string is not a valid constant name or constant is not defined



280
281
282
283
284
285
286
287
288
# File 'lib/core_ext/string.rb', line 280

def constantize
  unless (m = /\A(?:::)?([A-Z]\w*(?:::[A-Z]\w*)*)\z/.match(self))
    raise(NameError, "#{inspect} is not a valid constant name!")
  end

  # rubcop:disable Style/DocumentDynamicEvalDefinition
  Object.module_eval("::#{m[1]}", __FILE__, __LINE__) # ::Post
  # rubcop:enable Style/DocumentDynamicEvalDefinition
end

#dasherizeString

Replaces underscores (_) in a string with dashes (-). A helper method commonly used for URL slugs and CSS class names.

Examples:

"hello_world".dasherize #=> "hello-world"
"foo_bar_baz".dasherize #=> "foo-bar-baz"

Returns:

  • (String)

    The string with underscores replaced by dashes



299
300
301
# File 'lib/core_ext/string.rb', line 299

def dasherize
  tr('_', '-')
end

#demodulizeString

Removes the module part from a fully-qualified Ruby constant name, returning just the rightmost portion after the last double colon (::).

Examples:

Remove module namespace from fully-qualified name

"ActiveRecord::Base::Table".demodulize #=> "Table"

No change when no modules present

"String".demodulize #=> "String"

Returns:

  • (String)

    The final constant name without any module namespacing



314
315
316
# File 'lib/core_ext/string.rb', line 314

def demodulize
  gsub(/^.*::/, '')
end

#foreign_key(use_underscore: true) ⇒ String

Creates a foreign key name from a class name by removing any module namespacing, underscoring the remaining name, and appending ‘id’. The underscore before ‘id’ is optional.

Examples:

Basic usage

"Message".foreign_key #=> "message_id"

Without underscore

"Message".foreign_key(use_underscore: false) #=> "messageid"

With namespaced class

"Admin::Post".foreign_key #=> "post_id"

Parameters:

  • use_underscore (Boolean) (defaults to: true)

    Whether to include an underscore before ‘id’

Returns:

  • (String)

    The foreign key name



335
336
337
# File 'lib/core_ext/string.rb', line 335

def foreign_key(use_underscore: true)
  "#{demodulize.underscore}#{"_" if use_underscore}id"
end

#humanizeString

Converts a string into a more human-readable format by:

  • Removing any trailing ‘_id’

  • Converting underscores to spaces

  • Capitalizing the first letter

Examples:

Convert a database column name

"employee_salary".humanize #=> "Employee salary"

Remove ID suffix

"user_id".humanize #=> "User"

Basic conversion

"hello_world".humanize #=> "Hello world"

Returns:

  • (String)

    A human-friendly version of the string



355
356
357
# File 'lib/core_ext/string.rb', line 355

def humanize
  gsub(/_id$/, '').tr('_', ' ').capitalize
end

#pluralizeString

Transforms a word into its plural form according to standard English language rules and any custom rules defined through String.inflections.

If the word is in the uncountable list (e.g. “sheep”, “fish”), returns it unchanged. Otherwise applies plural transformation rules in order until one matches.

Examples:

Basic pluralization

"post".pluralize #=> "posts"
"octopus".pluralize #=> "octopi"

Uncountable words

"fish".pluralize #=> "fish"

Complex phrases

"the blue mailman".pluralize #=> "the blue mailmen"
"CamelOctopus".pluralize #=> "CamelOctopi"

Returns:

  • (String)

    The plural form of the word



378
379
380
381
382
383
384
# File 'lib/core_ext/string.rb', line 378

def pluralize
  result = dup
  unless Inflections.uncountables.include?(downcase)
    Inflections.plurals.each { |(rule, replacement)| break if result.gsub!(rule, replacement) }
  end
  result
end

#singularizeString

Transforms a word into its singular form according to standard English language rules and any custom rules defined through String.inflections.

If the word is in the uncountable list (e.g. “sheep”, “fish”), returns it unchanged. Otherwise applies singular transformation rules in order until one matches.

Examples:

Basic singularization

"posts".singularize #=> "post"
"matrices".singularize #=> "matrix"

Uncountable words

"fish".singularize #=> "fish"

Complex phrases

"the blue mailmen".singularize #=> "the blue mailman"
"CamelOctopi".singularize #=> "CamelOctopus"

Returns:

  • (String)

    The singular form of the word



405
406
407
408
409
410
411
# File 'lib/core_ext/string.rb', line 405

def singularize
  result = dup
  unless Inflections.uncountables.include?(downcase)
    Inflections.singulars.each { |(rule, replacement)| break if result.gsub!(rule, replacement) }
  end
  result
end

#tableizeString

Converts a class name or CamelCase word to a suitable database table name by underscoring and pluralizing it. Namespaces are converted to paths. Used to derive table names from model class names.

Examples:

Convert class name to table name

"RawScaledScorer".tableize #=> "raw_scaled_scorers"

Handle namespaces

"Admin::Post".tableize #=> "admin/posts"

Basic conversion

"fancyCategory".tableize #=> "fancy_categories"

Returns:

  • (String)

    The table name (underscored, pluralized form)



428
429
430
# File 'lib/core_ext/string.rb', line 428

def tableize
  underscore.pluralize
end

#titleizeString Also known as: titlecase

Converts a string into a more human-readable title format by:

  • Converting underscores and dashes to spaces

  • Capitalizing each word

  • Applying human-friendly formatting

titleize is also aliased as as titlecase

Examples:

Convert basic string to title

"hello_world".titleize #=> "Hello World"

Convert with special characters

"x-men: the last stand".titleize #=> "X Men: The Last Stand"

Convert camelCase to title

"camelCase".titleize #=> "Camel Case"

Returns:

  • (String)

    A titleized version of the string



450
451
452
# File 'lib/core_ext/string.rb', line 450

def titleize
  underscore.humanize.gsub(/\b([a-z])/) { |x| x[-1..].upcase }
end

#underscoreString

Converts a CamelCase or camelCase string into an underscored format.

  • Replaces ‘::’ with ‘/’ for namespace/path conversion

  • Adds underscores between words including:

    • Between runs of capital letters: ‘ABC’ -> ‘a_b_c’

    • Before first lowercase letter after capitals: ‘HTMLParser’ -> ‘html_parser’

    • Before capitals after lowercase/numbers: ‘fooBar’ -> ‘foo_bar’

  • Converts all dashes to underscores

  • Converts everything to lowercase

Examples:

Convert camelCase

"camelCase".underscore #=> "camel_case"
"ActiveRecord".underscore #=> "active_record"

Convert namespace

"ActiveRecord::Errors".underscore #=> 'active_record/errors'

Convert complex CamelCase

"HTMLParser".underscore #=> "html_parser"

Returns:

  • (String)

    The underscored version of the string



476
477
478
479
# File 'lib/core_ext/string.rb', line 476

def underscore
  gsub('::', '/').gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
                 .gsub(/([a-z\d])([A-Z])/, '\1_\2').tr('-', '_').downcase
end