module ActiveSupport::Inflector

def apply_inflections(word, rules)

apply_inflections('posts', inflections.singulars) # => "post"
apply_inflections('post', inflections.plurals) # => "posts"

Applies inflection rules for +singularize+ and +pluralize+.
def apply_inflections(word, rules)
  result = word.to_s.dup
  if word.empty? || inflections.uncountables.include?(result.downcase[/\b\w+\Z/])
    result
  else
    rules.each { |(rule, replacement)| break if result.sub!(rule, replacement) }
    result
  end
end

def camelize(term, uppercase_first_letter = true)

'SSLError'.underscore.camelize # => "SslError"

+underscore+, though there are cases where that does not hold:
As a rule of thumb you can think of +camelize+ as the inverse of

'active_model/errors'.camelize(:lower) # => "activeModel::Errors"
'active_model/errors'.camelize # => "ActiveModel::Errors"
'active_model'.camelize(:lower) # => "activeModel"
'active_model'.camelize # => "ActiveModel"

paths to namespaces.
+camelize+ will also convert '/' to '::' which is useful for converting

lowerCamelCase.
to +camelize+ is set to :lower then +camelize+ produces
By default, +camelize+ converts strings to UpperCamelCase. If the argument
def camelize(term, uppercase_first_letter = true)
  string = term.to_s
  if uppercase_first_letter
    string = string.sub(/^[a-z\d]*/) { inflections.acronyms[$&] || $&.capitalize }
  else
    string = string.sub(/^(?:#{inflections.acronym_regex}(?=\b|[A-Z_])|\w)/) { $&.downcase }
  end
  string.gsub(/(?:_|(\/))([a-z\d]*)/i) { "#{$1}#{inflections.acronyms[$2] || $2.capitalize}" }.gsub('/', '::')
end

def classify(table_name)

'business'.classify # => "Busines"

Singular names are not handled correctly:

'posts'.classify # => "Post"
'egg_and_hams'.classify # => "EggAndHam"

convert to an actual class follow +classify+ with +constantize+).
names to models. Note that this returns a string and not a Class (To
Create a class name from a plural table name like Rails does for table
def classify(table_name)
  # strip out any leading schema name
  camelize(singularize(table_name.to_s.sub(/.*\./, '')))
end

def const_regexp(camel_cased_word) #:nodoc:

:nodoc:
For instance, Foo::Bar::Baz will generate Foo(::Bar(::Baz)?)?
Mount a regular expression that will match part by part of the constant.
def const_regexp(camel_cased_word) #:nodoc:
  parts = camel_cased_word.split("::")
  last  = parts.pop
  parts.reverse.inject(last) do |acc, part|
    part.empty? ? acc : "#{part}(::#{acc})?"
  end
end

def constantize(camel_cased_word)

unknown.
NameError is raised when the name is not in CamelCase or the constant is

end
'C'.constantize # => 'outside', same as ::C
C # => 'inside'
C = 'inside'
module M
C = 'outside'

account:
whether it starts with "::" or not. No lexical context is taken into
The name is assumed to be the one of a top-level constant, no matter

'Test::Unit'.constantize # => Test::Unit
'Module'.constantize # => Module

Tries to find a constant with the name specified in the argument string.
def constantize(camel_cased_word)
  names = camel_cased_word.split('::')
  names.shift if names.empty? || names.first.empty?
  names.inject(Object) do |constant, name|
    if constant == Object
      constant.const_get(name)
    else
      candidate = constant.const_get(name)
      next candidate if constant.const_defined?(name, false)
      next candidate unless Object.const_defined?(name)
      # Go down the ancestors to check it it's owned
      # directly before we reach Object or the end of ancestors.
      constant = constant.ancestors.inject do |const, ancestor|
        break const    if ancestor == Object
        break ancestor if ancestor.const_defined?(name, false)
        const
      end
      # owner is in Object, so raise
      constant.const_get(name, false)
    end
  end
end

def dasherize(underscored_word)

'puni_puni'.dasherize # => "puni-puni"

Replaces underscores with dashes in the string.
def dasherize(underscored_word)
  underscored_word.tr('_', '-')
end

def deconstantize(path)

See also +demodulize+.

''.deconstantize # => ""
'::String'.deconstantize # => ""
'String'.deconstantize # => ""
'::Net::HTTP'.deconstantize # => "::Net"
'Net::HTTP'.deconstantize # => "Net"

Removes the rightmost segment from the constant expression in the string.
def deconstantize(path)
  path.to_s[0...(path.rindex('::') || 0)] # implementation based on the one in facets' Module#spacename
end

def demodulize(path)

See also +deconstantize+.

'Inflections'.demodulize # => "Inflections"
'ActiveRecord::CoreExtensions::String::Inflections'.demodulize # => "Inflections"

Removes the module part from the expression in the string.
def demodulize(path)
  path = path.to_s
  if i = path.rindex('::')
    path[(i+2)..-1]
  else
    path
  end
end

def foreign_key(class_name, separate_class_name_and_id_with_underscore = true)

'Admin::Post'.foreign_key # => "post_id"
'Message'.foreign_key(false) # => "messageid"
'Message'.foreign_key # => "message_id"

the method should put '_' between the name and 'id'.
+separate_class_name_and_id_with_underscore+ sets whether
Creates a foreign key name from a class name.
def foreign_key(class_name, separate_class_name_and_id_with_underscore = true)
  underscore(demodulize(class_name)) + (separate_class_name_and_id_with_underscore ? "_id" : "id")
end

def humanize(lower_case_and_underscored_word)

'author_id'.humanize # => "Author"
'employee_salary'.humanize # => "Employee salary"

output.
trailing "_id", if any. Like +titleize+, this is meant for creating pretty
Capitalizes the first word and turns underscores into spaces and strips a
def humanize(lower_case_and_underscored_word)
  result = lower_case_and_underscored_word.to_s.dup
  inflections.humans.each { |(rule, replacement)| break if result.sub!(rule, replacement) }
  result.gsub!(/_id$/, "")
  result.tr!('_', ' ')
  result.gsub(/([a-z\d]*)/i) { |match|
    "#{inflections.acronyms[match] || match.downcase}"
  }.gsub(/^\w/) { $&.upcase }
end

def inflections(locale = :en)

end
inflect.uncountable 'rails'
ActiveSupport::Inflector.inflections(:en) do |inflect|

Only rules for English are provided.
languages can be specified. If not specified, defaults to :en.
additional inflector rules. If passed an optional locale, rules for other
Yields a singleton instance of Inflector::Inflections so you can specify
def inflections(locale = :en)
  if block_given?
    yield Inflections.instance(locale)
  else
    Inflections.instance(locale)
  end
end

def ordinal(number)

ordinal(-1021) # => "st"
ordinal(-11) # => "th"
ordinal(1003) # => "rd"
ordinal(1002) # => "nd"
ordinal(2) # => "nd"
ordinal(1) # => "st"

in an ordered sequence such as 1st, 2nd, 3rd, 4th.
Returns the suffix that should be added to a number to denote the position
def ordinal(number)
  abs_number = number.to_i.abs
  if (11..13).include?(abs_number % 100)
    "th"
  else
    case abs_number % 10
      when 1; "st"
      when 2; "nd"
      when 3; "rd"
      else    "th"
    end
  end
end

def ordinalize(number)

ordinalize(-1021) # => "-1021st"
ordinalize(-11) # => "-11th"
ordinalize(1003) # => "1003rd"
ordinalize(1002) # => "1002nd"
ordinalize(2) # => "2nd"
ordinalize(1) # => "1st"

ordered sequence such as 1st, 2nd, 3rd, 4th.
Turns a number into an ordinal string used to denote the position in an
def ordinalize(number)
  "#{number}#{ordinal(number)}"
end

def parameterize(string, sep = '-')

# => Donald E. Knuth
<%= link_to(@person.name, person_path(@person)) %>

# => #
@person = Person.find(1)

end
end
"#{id}-#{name.parameterize}"
def to_param
class Person

a 'pretty' URL.
Replaces special characters in a string so that it may be used as part of
def parameterize(string, sep = '-')
  # replace accented chars with their ascii equivalents
  parameterized_string = transliterate(string)
  # Turn unwanted chars into the separator
  parameterized_string.gsub!(/[^a-z0-9\-_]+/i, sep)
  unless sep.nil? || sep.empty?
    re_sep = Regexp.escape(sep)
    # No more than one of the separator in a row.
    parameterized_string.gsub!(/#{re_sep}{2,}/, sep)
    # Remove leading/trailing separator.
    parameterized_string.gsub!(/^#{re_sep}|#{re_sep}$/i, '')
  end
  parameterized_string.downcase
end

def pluralize(word, locale = :en)

'ley'.pluralize(:es) # => "leyes"
'CamelOctopus'.pluralize # => "CamelOctopi"
'words'.pluralize # => "words"
'sheep'.pluralize # => "sheep"
'octopus'.pluralize # => "octopi"
'post'.pluralize # => "posts"

this parameter is set to :en.
pluralized using rules defined for that language. By default,
If passed an optional +locale+ parameter, the word will be

Returns the plural form of the word in the string.
def pluralize(word, locale = :en)
  apply_inflections(word, inflections(locale).plurals)
end

def safe_constantize(camel_cased_word)

'UnknownModule::Foo::Bar'.safe_constantize # => nil
'UnknownModule'.safe_constantize # => nil
'blargle'.safe_constantize # => nil

part of it) is unknown.
+nil+ is returned when the name is not in CamelCase or the constant (or

end
'C'.safe_constantize # => 'outside', same as ::C
C # => 'inside'
C = 'inside'
module M
C = 'outside'

account:
whether it starts with "::" or not. No lexical context is taken into
The name is assumed to be the one of a top-level constant, no matter

'Test::Unit'.safe_constantize # => Test::Unit
'Module'.safe_constantize # => Module

Tries to find a constant with the name specified in the argument string.
def safe_constantize(camel_cased_word)
  constantize(camel_cased_word)
rescue NameError => e
  raise unless e.message =~ /(uninitialized constant|wrong constant name) #{const_regexp(camel_cased_word)}$/ ||
    e.name.to_s == camel_cased_word.to_s
rescue ArgumentError => e
  raise unless e.message =~ /not missing constant #{const_regexp(camel_cased_word)}\!$/
end

def singularize(word, locale = :en)

'leyes'.singularize(:es) # => "ley"
'CamelOctopi'.singularize # => "CamelOctopus"
'word'.singularize # => "word"
'sheep'.singularize # => "sheep"
'octopi'.singularize # => "octopus"
'posts'.singularize # => "post"

this parameter is set to :en.
pluralized using rules defined for that language. By default,
If passed an optional +locale+ parameter, the word will be

string.
The reverse of +pluralize+, returns the singular form of a word in a
def singularize(word, locale = :en)
  apply_inflections(word, inflections(locale).singulars)
end

def tableize(class_name)

'fancyCategory'.tableize # => "fancy_categories"
'egg_and_ham'.tableize # => "egg_and_hams"
'RawScaledScorer'.tableize # => "raw_scaled_scorers"

method uses the +pluralize+ method on the last word in the string.
Create the name of a table like Rails does for models to table names. This
def tableize(class_name)
  pluralize(underscore(class_name))
end

def titleize(word)

'raiders_of_the_lost_ark'.titleize # => "Raiders Of The Lost Ark"
'TheManWithoutAPast'.titleize # => "The Man Without A Past"
'x-men: the last stand'.titleize # => "X Men: The Last Stand"
'man from the boondocks'.titleize # => "Man From The Boondocks"

+titleize+ is also aliased as +titlecase+.

output. It is not used in the Rails internals.
create a nicer looking title. +titleize+ is meant for creating pretty
Capitalizes all the words and replaces some characters in the string to
def titleize(word)
  humanize(underscore(word)).gsub(/\b(?<!['’`])[a-z]/) { $&.capitalize }
end

def transliterate(string, replacement = "?")

# => "Juergen"
transliterate('Jürgen')
I18n.locale = :de

# => "Jurgen"
transliterate('Jürgen')
I18n.locale = :en

Now you can have different transliterations for each locale:

})
}
rule: ->(string) { MyTransliterator.transliterate(string) }
transliterate: {
I18n.backend.store_translations(:de, i18n: {

complex requirements, a Proc:
maps characters to ASCII approximations as shown above, or, for more
The value for i18n.transliterate.rule can be a simple Hash that

})
}
}
'ö' => 'oe'
'ü' => 'ue',
rule: {
transliterate: {
I18n.backend.store_translations(:de, i18n: {
# Or set them using Ruby

ö: "oe"
ü: "ue"
rule:
transliterate:
i18n:
# Store the transliterations in locales/de.yml

them as the i18n.transliterate.rule i18n key:
In order to make your custom transliterations available, you must set

to ASCII.
and "ö" to "ue" and "oe", or to add support for transliterating Russian
locale. This can be useful, for example, to transliterate German's "ü"
This method is I18n aware, so you can set up custom approximations for a

e.g, "ø", "ñ", "é", "ß", etc.
Default approximations are provided for Western/Latin characters,

# => "AEroskobing"
transliterate('Ærøskøbing')

exists, a replacement character which defaults to "?".
Replaces non-ASCII characters with an ASCII approximation, or if none
def transliterate(string, replacement = "?")
  I18n.transliterate(ActiveSupport::Multibyte::Unicode.normalize(
    ActiveSupport::Multibyte::Unicode.tidy_bytes(string), :c),
      :replacement => replacement)
end

def underscore(camel_cased_word)

'SSLError'.underscore.camelize # => "SslError"

+camelize+, though there are cases where that does not hold:
As a rule of thumb you can think of +underscore+ as the inverse of

'ActiveModel::Errors'.underscore # => "active_model/errors"
'ActiveModel'.underscore # => "active_model"

Changes '::' to '/' to convert namespaces to paths.

Makes an underscored, lowercase form from the expression in the string.
def underscore(camel_cased_word)
  word = camel_cased_word.to_s.dup
  word.gsub!('::', '/')
  word.gsub!(/(?:([A-Za-z\d])|^)(#{inflections.acronym_regex})(?=\b|[^a-z])/) { "#{$1}#{$1 && '_'}#{$2.downcase}" }
  word.gsub!(/([A-Z\d]+)([A-Z][a-z])/,'\1_\2')
  word.gsub!(/([a-z\d])([A-Z])/,'\1_\2')
  word.tr!("-", "_")
  word.downcase!
  word
end