Module: Mongoid::Extensions::String::Inflections

Included in:
String
Defined in:
lib/mongoid/extensions/string/inflections.rb

Overview

This module contains convenience methods for string inflection and conversion.

Constant Summary collapse

CHAR_CONV =

Represents how special characters will get converted when creating a composite key that should be unique and part of a url.

{
  " " => "-",
  "!" => "-excl-",
  "\"" => "-dblquo-",
  "#" => "-hash-",
  "$" => "-dol-",
  "%" => "-perc-",
  "&" => "-and-",
  "'" => "-quo-",
  "(" => "-oparen-",
  ")" => "-cparen-",
  "*" => "-astx-",
  "+" => "-plus-",
  "," => "-comma-",
  "-" => "-",
  "." => "-period-",
  "/" => "-fwdslsh-",
  ":" => "-colon-",
  ";" => "-semicol-",
  "<" => "-lt-",
  "=" => "-eq-",
  ">" => "-gt-",
  "?" => "-ques-",
  "@" => "-at-",
  "[" => "-obrck-",
  "\\" => "-bckslsh-",
  "]" => "-clbrck-",
  "^" => "-carat-",
  "_" => "-undscr-",
  "`" => "-bcktick-",
  "{" => "-ocurly-",
  "|" => "-pipe-",
  "}" => "-clcurly-",
  "~" => "-tilde-"
}
REVERSALS =
{
  "asc" => "desc",
  "ascending" => "descending",
  "desc" => "asc",
  "descending" => "ascending"
}

Instance Method Summary collapse

Instance Method Details

#collectionizeString

Convert the string to a collection friendly name.

Examples:

Collectionize the string.

"namespace/model".collectionize

Returns:

  • (String)

    The string in collection friendly form.



67
68
69
# File 'lib/mongoid/extensions/string/inflections.rb', line 67

def collectionize
  tableize.gsub("/", "_")
end

#identifyString

Convert this string to a key friendly string.

Examples:

Convert to key.

"testing".identify

Returns:

  • (String)

    The key friendly string.



77
78
79
80
81
82
83
84
# File 'lib/mongoid/extensions/string/inflections.rb', line 77

def identify
  if Mongoid.parameterize_keys
    key = ""
    each_char { |c| key += (CHAR_CONV[c] || c.downcase) }; key
  else
    self
  end
end

#invertString

Get the inverted sorting option.

Examples:

Get the inverted option.

"asc".invert

Returns:

  • (String)

    The string inverted.



92
93
94
# File 'lib/mongoid/extensions/string/inflections.rb', line 92

def invert
  REVERSALS[self]
end

#readerString

Get the string as a getter string.

Examples:

Get the reader/getter

"model=".reader

Returns:

  • (String)

    The string stripped of “=”.



102
103
104
# File 'lib/mongoid/extensions/string/inflections.rb', line 102

def reader
  delete("=")
end

#writer?true, false

Is this string a writer?

Examples:

Is the string a setter method?

"model=".writer?

Returns:

  • (true, false)

    If the string contains “=”.



112
113
114
# File 'lib/mongoid/extensions/string/inflections.rb', line 112

def writer?
  include?("=")
end