Class: String
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
-
.inflections {|Inflections| ... } ⇒ Inflections
Provides access to the Inflections module for defining custom inflection rules.
Instance Method Summary collapse
-
#blank? ⇒ true, false
Returns true if the string consists entirely of whitespace characters.
-
#camelize(first_letter_in_uppercase = :upper) ⇒ String
(also: #camelcase)
Converts the string to CamelCase format.
-
#classify ⇒ String
Converts a string into a class name by removing any non-final period and subsequent characters, converting to singular form, and camelizing.
-
#constantize ⇒ Object
Finds and returns a Ruby constant from a string name.
-
#dasherize ⇒ String
Replaces underscores (_) in a string with dashes (-).
-
#demodulize ⇒ String
Removes the module part from a fully-qualified Ruby constant name, returning just the rightmost portion after the last double colon (::).
-
#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’.
-
#humanize ⇒ String
Converts a string into a more human-readable format by: - Removing any trailing ‘_id’ - Converting underscores to spaces - Capitalizing the first letter.
-
#pluralize ⇒ String
Transforms a word into its plural form according to standard English language rules and any custom rules defined through String.inflections.
-
#singularize ⇒ String
Transforms a word into its singular form according to standard English language rules and any custom rules defined through String.inflections.
-
#tableize ⇒ String
Converts a class name or CamelCase word to a suitable database table name by underscoring and pluralizing it.
-
#titleize ⇒ String
(also: #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.
-
#underscore ⇒ String
Converts a CamelCase or camelCase string into an underscored format.
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.
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
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’)
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 |
#classify ⇒ String
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.
258 259 260 |
# File 'lib/core_ext/string.rb', line 258 def classify sub(/.*\./, '').singularize.camelize end |
#constantize ⇒ Object
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.
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 |
#dasherize ⇒ String
Replaces underscores (_) in a string with dashes (-). A helper method commonly used for URL slugs and CSS class names.
299 300 301 |
# File 'lib/core_ext/string.rb', line 299 def dasherize tr('_', '-') end |
#demodulize ⇒ String
Removes the module part from a fully-qualified Ruby constant name, returning just the rightmost portion after the last double colon (::).
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.
335 336 337 |
# File 'lib/core_ext/string.rb', line 335 def foreign_key(use_underscore: true) "#{demodulize.underscore}#{"_" if use_underscore}id" end |
#humanize ⇒ String
Converts a string into a more human-readable format by:
-
Removing any trailing ‘_id’
-
Converting underscores to spaces
-
Capitalizing the first letter
355 356 357 |
# File 'lib/core_ext/string.rb', line 355 def humanize gsub(/_id$/, '').tr('_', ' ').capitalize end |
#pluralize ⇒ String
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.
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 |
#singularize ⇒ String
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.
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 |
#tableize ⇒ String
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.
428 429 430 |
# File 'lib/core_ext/string.rb', line 428 def tableize underscore.pluralize end |
#titleize ⇒ String 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
450 451 452 |
# File 'lib/core_ext/string.rb', line 450 def titleize underscore.humanize.gsub(/\b([a-z])/) { |x| x[-1..].upcase } end |
#underscore ⇒ String
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
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 |