Module: AegisNet::StringNormalizr::InstanceMethods
- Defined in:
- lib/string_normalizr.rb
Instance Method Summary collapse
-
#normalize(options = {}) ⇒ Object
Returns a new String based on pre-defined normalization rules.
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 withstror set tofalseto 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"
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( = {}) # shamelessly taken from ActiveSupport::ActiveSupport::Hash::Keys#assert_valid_keys valid_keys = [:replace_whitespaces, :strip] unknown_keys = .keys - [valid_keys].flatten raise(ArgumentError, "Unknown key(s): #{unknown_keys.join(", ")}") unless unknown_keys.empty? # Default options = { :downcase => false, :strip => true, :replace_whitespaces => "-" }.merge() n_str = AegisNet::StringNormalizr::COLLATION.inject(dup) {|str, (collate_from, collate_to)| str.gsub(collate_from, collate_to)} n_str.strip! if [:strip] n_str.gsub!(/\s+/, [:replace_whitespaces]) if [:replace_whitespaces] n_str end |