Class: Uncsv::KeyNormalizer
- Inherits:
-
Object
- Object
- Uncsv::KeyNormalizer
- Defined in:
- lib/uncsv/key_normalizer.rb
Overview
Normalizes strings into a consistant format
Constant Summary collapse
- DEFAULTS =
The default values applied if an attribute's value is not specified when constructing a new
KeyNormalizer
object. { downcase: true, separator: '_' }.freeze
Instance Attribute Summary collapse
-
#downcase ⇒ Boolean
Sets keys to all lower-case if set to
true
. -
#separator ⇒ String
A string to replace all non-alphanumeric characters in the key.
Instance Method Summary collapse
-
#initialize(opts = {}) ⇒ KeyNormalizer
constructor
Create a new
KeyNormalizer
object. -
#normalize(key) ⇒ String?
Normalize a key.
Constructor Details
#initialize(opts = {}) ⇒ KeyNormalizer
Create a new KeyNormalizer
object.
Options will be set to the defaults unless overridden by the opts
parameter.
35 36 37 |
# File 'lib/uncsv/key_normalizer.rb', line 35 def initialize(opts = {}) DEFAULTS.merge(opts).each { |k, v| public_send("#{k}=", v) } end |
Instance Attribute Details
#downcase ⇒ Boolean
Sets keys to all lower-case if set to true
Default: true
26 27 28 |
# File 'lib/uncsv/key_normalizer.rb', line 26 def downcase @downcase end |
#separator ⇒ String
A string to replace all non-alphanumeric characters in the key
Default: '_'. Can be set to an empty string to remove non-alphanumeric characters without replacing them.
19 20 21 |
# File 'lib/uncsv/key_normalizer.rb', line 19 def separator @separator end |
Instance Method Details
#normalize(key) ⇒ String?
Normalize a key
Replaces non-alphanumeric characters with separator
, then
deduplicates underscores and trims them from the ends of the key. Then
the key is lower-cased if downcase
is set.
48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/uncsv/key_normalizer.rb', line 48 def normalize(key) return nil if key.nil? key = key.gsub(/[^a-z0-9]+/i, separator) unless separator.empty? escaped_separator = Regexp.escape(separator) key.gsub!(/#{escaped_separator}{2,}/, separator) key.gsub!(/^#{escaped_separator}|#{escaped_separator}$/, '') end key.downcase! if downcase key end |