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

  • :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)


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

def normalize(options = {})
  # shamelessly taken from ActiveSupport::ActiveSupport::Hash::Keys#assert_valid_keys
  valid_keys = [: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.gsub!(/\s+/, options[:replace_whitespaces]) if options[:replace_whitespaces]
  n_str
end