Module: AegisNet::StringNormalizr::InstanceMethods

Defined in:
lib/string_normalizr.rb

Instance Method Summary collapse

Instance Method Details

#normalize(options = {}) ⇒ Object

Returns a new String based on pre-defined normalization rules

Parameters

  • options: optional Hash for normalization customization

Available options

  • :downcase - convert to lower case (true|false, default: false)

  • :strip - trim leading and trailing whitespaces (true|false, default: true)

  • :replace_whitespaces - replace whitespaces within the string with str or set to false to leave whitespaces alone. Makes little sense w/o :strip => true (str|false, default: “-”)

Examples

"This is án exåmple".normalize
 => "This-is-an-example

"Tëst string with träiling whitespaces   ".normalize(:replace_whitespaces => false)
 => "Test string with traeiling whitespaces"

Raises:

  • (ArgumentError)


87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/string_normalizr.rb', line 87

def normalize(options = {})
  # shamelessly taken from ActiveSupport::ActiveSupport::Hash::Keys#assert_valid_keys
  valid_keys = [:downcase, :replace_whitespaces, :strip]
  unknown_keys = options.keys - [valid_keys].flatten
  raise(ArgumentError, "Unknown key(s): #{unknown_keys.join(", ")}") unless unknown_keys.empty?

  # Default options
  options = {
    :downcase            => false,
    :strip               => true,
    :replace_whitespaces => "-"
  }.merge(options)

  n_str = AegisNet::StringNormalizr::COLLATION.inject(dup) {|str, (collate_from, collate_to)| str.gsub(collate_from, collate_to)}
  n_str.strip!    if options[:strip]
  n_str.downcase! if options[:downcase]
  n_str.gsub!(/\s+/, options[:replace_whitespaces]) if options[:replace_whitespaces]
  n_str
end

#normalize!(options = {}) ⇒ Object

Performs the changes of AegisNet::StringNormalizr#normalize in place, returning the new string.

See AegisNet::StringNormalizr#normalize for the optional parameter hash.



111
112
113
# File 'lib/string_normalizr.rb', line 111

def normalize!(options = {})
  self.replace(self.normalize(options))
end