Module: Idxfence::Inflector

Defined in:
lib/idxfence/inflector.rb

Overview

A small, deliberately conservative stand-in for ActiveSupport::Inflector -- just enough of Rails' own table-name-inference convention (Model.name.demodulize.underscore.pluralize) to resolve a model's default table name without requiring an actual Rails/ActiveSupport installation. See DETAILS.md's "table-name inference" section for exactly which pluralization rules are (and are not) implemented, and why self.table_name = "..." is honored as an explicit override rather than something idxfence tries to out-guess.

Constant Summary collapse

UNCOUNTABLE =
%w[series species equipment information news].freeze
IRREGULAR =
{
  "person" => "people",
  "man" => "men",
  "woman" => "women",
  "child" => "children",
  "tooth" => "teeth",
  "foot" => "feet",
  "mouse" => "mice",
  "goose" => "geese"
}.freeze

Class Method Summary collapse

Class Method Details

.demodulize(class_name) ⇒ Object

"Admin::UserAccount" -> "UserAccount" (only the last namespace segment -- matches Rails' default table_name_prefix-less behavior; a project that sets a custom table_name_prefix isn't modeled here, see DETAILS.md).



30
31
32
# File 'lib/idxfence/inflector.rb', line 30

def demodulize(class_name)
  class_name.to_s.split("::").last.to_s
end

.pluralize(word) ⇒ Object

"user_account" -> "user_accounts" (a deliberately small rule set, not a full English pluralizer -- see DETAILS.md limitations).



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/idxfence/inflector.rb', line 44

def pluralize(word)
  return word if UNCOUNTABLE.include?(word)
  return IRREGULAR[word] if IRREGULAR.key?(word)

  case word
  when /(ch|sh|ss|x|z)\z/
    "#{word}es"
  when /[^aeiou]y\z/
    "#{word[0..-2]}ies"
  when /(fe)\z/
    "#{word[0..-3]}ves"
  when /[^f]f\z/
    "#{word[0..-2]}ves"
  when /s\z/
    word
  else
    "#{word}s"
  end
end

.table_name_for(class_name) ⇒ Object

Rails' own default: Model.name.demodulize.underscore.pluralize.



65
66
67
# File 'lib/idxfence/inflector.rb', line 65

def table_name_for(class_name)
  pluralize(underscore(demodulize(class_name)))
end

.underscore(camel) ⇒ Object

"UserAccount" -> "user_account"



35
36
37
38
39
40
# File 'lib/idxfence/inflector.rb', line 35

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